IF construction
The if construction is one of bash's bases and its syntax is:
else block is optional.
Example 2: String comparisons with regular expression
Example 3: Numeric comparisons
Example 4: Checking files
if TEST-COMMANDS; then
CONSEQUENT-COMMANDS;
else
CONSEQUENT-ELSE-COMMANDS;
fi
Examples:
Example 1: String comparisonsvar="..."
if [ ${var} = "text" ]
then
echo "true";
else
echo "false";
fi
var="..."
if [[ ${var} == tex* ]]
then
echo "true";
else
echo "false";
fi
var="..."
if [ ${var} -gt "10" ]
then
echo "....";
fi
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:
Example 2: Using the content of a variable to specify LIST items:
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
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
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