|
|
After if..else and if..elfi..else we move to looping structures. Looping is supported in the form of for and while. Again they work semantically the same but syntactically different.
for Loop
Syntax
In bash shell there are two syntaxes.
1. for variable in list
do
statement1 is executed till the list exhausts
done
2. traditional for
for (( variable_init ; condition ; variable_increment/decrement ))
do
statement1 is executed
till the condition returns false
done
Example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for i in 1 2 3 4 5 | |
do | |
echo "Testing $i times" | |
done |
Same program with second syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Here the spaces are for formatting purposes only.for is not sensitive to spaces | |
for (( i=0 ; i<=5 ; i++ )) | |
do | |
echo "Testing $i times" | |
done |
while Loop
Nothing new about it. Just loops through the series of statements until the condition is true.
Syntax:
#sensitive to white spaces
while [ condition ]
do
statement1
statement2
done
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo "Enter the number" | |
read x | |
#initialize looping variable | |
i=0 | |
#check if i is less than 10 | |
while [ $i -le 10 ] | |
do | |
#print the value of x * i | |
echo " $x * $i = $(( $x * $i ))" | |
#increment i by 1 | |
i=$(( $i + 1 )) | |
done |
case Statement
case in bash scripting is very similar to switch case semantically . It save the trouble for writing a multilevel elif statements.
Syntax:
case $variable in
case1) statement1;;
case2) statement2;;
..
..
caseN) statementN;;
esac
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo "Enter the number" | |
read x | |
case $x in | |
1) echo "You entered one";; | |
2) echo "You entered two";; | |
3) echo "You entered three";; | |
4) echo "You entered four";; | |
5) echo "You entered five";; | |
*) echo "Sorry not listed";; | |
esac |
No comments:
Post a Comment