Linux Tutorials
Building Hadoop Clusters On Linux In EC2
Installing And Using Hadoop
Setting Up SSH Keys Using SSH Agents And Tunnels
Creating OpenSSL Certificates and Certificate Authorities
Installing and configuring Xen
IPTables Primer
Linux Basic Bash Scripting

Linux Basic Bash Scripting

Loops

while loops

While loops are used to execute a list of commands repetivily as long as a condition is true.

Example:

while [ -a tmp.LOCK ]
do
/bin/sleep 1
done
/bin/touch tmp.LOCK

This example script checks to see if a lock file exists. If the lock file exists we execute the sleep statement to wait one second before checking if the lock is available again. This is done to cut down on CPU load. Once the other application that used the lock file deletes it we use the touch command to create the lock file for our uses. The touch command simply checks to see if it can obtain write access to a file by updating the timestamp on the file.

until loops

The until loop is the exact opposite of the while loop. The until loop executes lists of code until a condition is met.
Example:

#!/bin/bash

i=1

until [ $i -gt 5 ]
do
echo "Time $i through the loop"
i=$[$i+1]
done

We kept it real simple in this example. This loop just echos what time through the loop it is. We use the variable i to count the number of times through the loop.

for loops

For loops operate differently than while and until loops. For loops are commonly used to operate on lists.
Example:

#!/bin/bash

for PORT in 25 113 139
do
/usr/sbin/iptables -A INPUT -s 0.0.0.0 -p tcp --destination-port $PORT -j DRROP
done

This simple script executes an iptables rule to block the ports in the list on the for statement line. Each time through the script one of the port numbers is stored in the variable PORT and the code is executed.

More conditional statements and exit status codes <<  1 2 3 4 5
New Content