bash if bash elif bash case statement

Conditionals statement in bash or shell script

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

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

Bash if bash elif

If [ conditional expression1 ] then
statement1
statement2
.
elif [ conditional expression2 ] then
statement3
statement4
.
else
statement5
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

 

Some rules to be follow while using conditions in bash script

i) Always keep space between square brackets.

ii) It is good habit to use quote for string variable as string variable may contain space

Understanding some conditional statement syntax

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
For numeric comparison we use eq, ne,lt and gt.
But for double brackets for comparison we can use ==, !=, <, and > .

 


You May Also Enjoy Reading This …

Leave a Reply

Your email address will not be published. Required fields are marked *