Conditionals statement in bash or shell script
conditional statements is used for making correct decisions and perform the right actions on it.
if statement in shell script
1) if…fi statement
2) if…else…fi statement
3) if…elif…else…fi statement
Switch case in Bash script
case…esac statement
Bash if Statement
if [conditional expression]; then
Statement or command if ‘conditional expression’ is true.
fi
#!/bin/bash echo "Enter numeric value: " read value if [ $value -gt 10 ]; then echo "Value is greater than 10" fi
Bash if else
if [conditional expression]; then
Statement or command if ‘conditional expression’ is true.
else
Statement or command if ‘conditional expression’ is false.
fi
#!/bin/bash echo "Enter numeric value: " read value if [ $value -gt 10 ]; then echo "Value is greater than 10" else echo "Value is less than 10" fi
Bash if bash elif
If [ conditional expression1 ]
then
statement1
statement2
.
elif [ conditional expression2 ]
then
statement3
statement4
.
else
statement5
fi
#!/bin/bash Num=55 if [ $Num-eq 60 ];then echo "Number is 60" elif [ $Num-gt 60 ]; then echo "Number is greater than 60" else echo "Number is less than 60" fi
Bash case statement
case $variable in
pattern-1)
commands
;;
pattern-2)
commands
;;
pattern-3|pattern-4|pattern-5)
commands
;;
pattern-N)
commands
;;
*)
commands
;;
esac
Example
#!/bin/bash echo "Please Enter Number between 1 to 3 " read Num case $Num in 1) echo "You Have enter One" ;; 2) echo "You Have enter Two" ;; 3) echo "You Have enter Three" ;; *) echo "Sorry you have enter wrong nmber" ;; esac
Some rules to be follow while using conditions in bash script
i) Always keep space between square brackets.
if [$num -gt 25]; then # this will not work
# correct syntax is if [ $num -gt 25 ]; then # this is right syntax
ii) It is good habit to use quote for string variable as string variable may contain space
if [ "$num1" -ge "num2" ]; then
Understanding some conditional statement syntax
#!/bin/sh file="/home/file.txt" if [ -e $file ]; then echo "File exists" else echo "File does not exist" fi
here we used -e option for file exists ,you may check some more option in our previous lessen.
Different between Double bracket and Single bracket in bash conditional statement
[ ] Single Bracket is POSIX shell to to enclose a conditional expression
[[ ]] Double Brackets is an enhance version of POSIX, which is supported by bash and other shells(zsh,ksh).
[ is a bash Builtin
[[ ]] are bash Keywords
if [ a < b ]; then # it will give an error if [[ a < b ]]; then # this will work fine
For numeric comparison we use eq, ne,lt and gt.
But for double brackets for comparison we can use ==, !=, <, and > .
if [ Num1 lt Num2 ]; then #No Error if [ Num1 < Num2 ]; then #Error: Num2 No such file or directory if [ Num1 \< Num2]; then #No Error ,It work with Escape if [[ Num1 < Num2]]; then #No Error
You May Also Enjoy Reading This …