Monday, 21 August 2017

Bash scripting - examples of constructions (if else, for loop, while loop, until loop)

IF construction

The if construction is one of bash's bases and its syntax is:
 if TEST-COMMANDS; then 
     CONSEQUENT-COMMANDS; 
 else
     CONSEQUENT-ELSE-COMMANDS; 
 fi
else block is optional.

Examples:

Example 1: String comparisons
var="..."
if  [ ${var} = "text" ] 
then
   echo "true";
else
   echo "false";
fi
Example 2: String comparisons with regular expression
var="..."
if  [[ ${var} == tex* ]] 
then
   echo "true";
else
   echo "false";
fi
Example 3: Numeric comparisons
var="..."
if  [ ${var} -gt "10" ] 
then
   echo "....";
fi
Example 4: Checking files
if  [ -f file.txt ]
then
   echo "file.txt exists";
fi

For loop construction

The for loop construction is one of bash's bases and its syntax is:
 for NAME [in LIST ]; do
     COMMANDS; 
 done

Examples:

Example 1: Using command substitution for specifying LIST items:
for i in `cat list.xml`; do 
    cp "$i" "$i".txt ; 
done
Example 2: Using the content of a variable to specify LIST items:
LIST="$(ls *.xml)"
for i in "$LIST"; do
     cp "$i" "$i".txt ; 
done

While loop construction

The while construct allows for repetitive execution of a list of commands, as long as the command controlling the while loop executes successfully (exit status of zero). 
Its syntax is:
 while CONTROL-COMMAND; do
     COMMANDS; 
 done

Examples:

Example 1: Simple example using while.
 while test $index -lt $number; do
     index=$[$index+1];
 done
Example 2: infinite while loop, implement a timer. You can use "CTRL" + "z" to stop the script.
 while true; do
        date +"%T";
        sleep 1;
        clear;
 done

Until loop construction

The until loop is very similar to the while loop, except that the loop executes until the TEST-COMMAND executes successfully. As long as this command fails, the loop continues. The syntax is the same as for the while loop:
 until TEST-COMMAND; do
     COMMANDS; 
 done

Example:

Create a simple script for disk space monitor on your home:
while true; do 
    DISKSPACE=$(df -h $WEBDIR | grep -v File | awk '{print $5 }' | cut -d "%" -f1 -)
    
    until [ $DISKSPACE -ge "90" ]; do 
        alert "disk space 90%";
    done
    
done 

Internal Links

May be of interest to you:

No comments:

Post a Comment

Welcome

Hello everybody, Welcome in my blog called "Information technology archive". Obviously the topics will be related to Informatio...