Conditional Statements

if statement

if [ expression ] 
then 
	statement
fi

if-else statement

if [ expression ]
then
   statement1
else
   statement2
fi

else-if ladder

if [ expression1 ]
then
   statement1
elif [ expression2 ]
then
   statement2
else
   statement3
fi

Nested if

if [ expression1 ]
then
   statement1
else
   if [ expression2 ]
   then
      statement2
   fi
fi

switch statement

case "$var"  in
   Pattern-1) Statement 1;;
   Pattern-2) Statement 1;;

   Pattern-n) Statement n;;
esac
# example

CARS="bmw"
  
#Pass the variable in string 
case "$CARS" in 
    #case 1 
    "mercedes") echo "Headquarters - Affalterbach, Germany" ;; 
      
    #case 2 
    "audi") echo "Headquarters - Ingolstadt, Germany" ;; 
      
    #case 3 
    "bmw") echo "Headquarters - Chennai, Tamil Nadu, India" ;; 

		# any other case i.e., default case
		* ) echo "N/A" ;;
esac

Looping statements

while loop

Here statements are executed when the condition holds true.

while [ condition ]
do 
	statements
done

Example: Reading the contents of a file using while and I/O redirection and pipes (respectively)

#! /bin/bash
# using I/O redirection
while read p
do 
	echo "$p"
done < file.txt
#! /bin/bash
# using pipes
cat file.txt | while read p
do 
	echo "$p"
done

until loop

Here the statements are executed only when the condition is false.

until [ condition ]
do 
	statements
done

for loop

for (( EXP1; EXP2; EXP3 ))
do
	commands
done
for variable in 1 2 3 ... N
do 
	commands
done
for variable in file1 file2 file3
do 
	commands on $variable
done
for output in $(linux-commands-here)
do
	commands on $output

Examples:

#! /bin/bash
for iter in 1 2 3 4 5
do 
	echo "$iter"
done
#! /bin/bash
# this will work only for bash version greater than 4.0
# range is specified using {START..END..INCREMENT} 
# range is inclusive of START & END
# INCREMENT can be skipped - if skipped defaults to 1
for iter in {1..10}
do 
	echo "$iter"
done
#! /bin/bash
for (( i=0; i<5; i++ ))
do
	echo $i
done
#! /bin/bash
for commands in ls pwd date
do
	echo "---$command---" # print command name
	$command # execute command
done