1 .Shell Scripting- if control STATEment programS
Conditional Statements: There are a total of five conditional statements which can be used in bash programming.
if statement
This block will process if specified condition is true. Syntax:
if [ expression ] then
statement
fi
An example of the code:
#Initializing two variables a=20
b=20
if [ $a == $b ] then
#If they are equal then print this echo “a is equal to b”
else
#else print this
echo “a is not equal to b”
fi
if-else statement
If specified condition is not true in if part then else part will be executed. Syntax:
if [ expression ] then
statement1 else
statement2
fi
if..elif..else..fi statement (Else If ladder)
To use multiple conditions in one if-else block, then the elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the conditions is true then it processes else part.
Syntax:
if [ expression1 ] then
statement1 statement2
.
.
elif [ expression2 ] then
statement3 statement4
.
.
else
statement5
fi
2. Shell Scripting- while control statement.
While Statement
Here command is evaluated and based on the result loop will executed, if command raise to false then loop will be terminated
Syntax
while [CONDITION] do
[COMMANDS]
done Copy
The while statement starts with the while keyword, followed by the conditional expression.
The condition is evaluated before executing the commands. If the condition evaluates to true, commands are executed. Otherwise, if the condition evaluates to false, the loop is terminated, and the program control will be passed to the command that follows.
In the example below, on each iteration, the current value of the variable i is printed and incremented by one.
i=0
while [ $i -le 2 ] do
echo Number: $i ((i++))
done Copy
loop iterates as long as i is less or equal than two. It will produce the following output:
Number: 0
Number: 1
Number: 2
3 . Shell Scripting- for control statement.
For Statement
The for loop operate on lists of items. It repeats a set of commands for every item in a list.
Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN.
Syntax
for var in word1 word2 …wordn do
Statement to be executed done
example
#Start of for loop
for a in 1 2 3 4 5 6 7 8 9 10 do
# if a is equal to 5 break the loop if [ $a == 5 ]
then
break
fi
# Print the value echo “Iteration no $a”
done Output
$bash -f main.sh Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4