Conditionals let you decide whether to perform an action or not, this decision is taken by evaluating an expression.
Conditionals have many forms. The most basic form is: if expression then statement where 'statement' is only executed if 'expression' evaluates to true. '2<1' is an expresion that evaluates to false, while '2>1' evaluates to true.xs
Conditionals have other forms such as: if expression then statement1 else statement2. Here 'statement1' is executed if 'expression' is true,otherwise 'statement2' is executed.
Yet another form of conditionals is: if expression1 then statement1 else if expression2 then statement2 else statement3. In this form there's added only the "ELSE IF 'expression2' THEN 'statement2'" which makes statement2 being executed if expression2 evaluates to true. The rest is as you may imagine (see previous forms).
A word about syntax:
The base for the 'if' constructions in bash is this:
if [expression];
then
code if 'expression' is true.
fi
#!/bin/bash if [ "foo" = "foo" ]; then echo expression evaluated as true fi
The code to be executed if the expression within braces is true can be found after the 'then' word and before 'fi' which indicates the end of the conditionally executed code.
#!/bin/bash if [ "foo" = "foo" ]; then echo expression evaluated as true else echo expression evaluated as false fi
if [ condition ] # true = 0 then # condition is true elif [ condition1 ] then # condition1 is true elif condition2 then # condition2 is tru else # None of the conditions is true fi
#!/bin/bash T1="foo" T2="bar" if [ "$T1" = "$T2" ]; then echo expression evaluated as true else echo expression evaluated as false fi
expression in pattern1|pattern2|pattern3) execute commands ;; pattern4) execute commands ;; pattern5) execute commands ;; *) esac
#!/bin/bash # if no command line arg given # set rental to Unknown if [ -z $1 ] then rental="*** Unknown vehicle ***" elif [ -n $1 ] then # otherwise make first arg as a rental rental=$1 fi case $rental in "car") echo "For $rental rental is Rs.20 per k/m.";; "van") echo "For $rental rental is Rs.10 per k/m.";; "jeep") echo "For $rental rental is Rs.5 per k/m.";; "bicycle") echo "For $rental rental 20 paisa per k/m.";; "enfield") echo "For $rental rental Rs.3 per k/m.";; "thunderbird") echo "For $rental rental Rs.5 per k/m.";; *) echo "Sorry, I can not get a $rental rental for you!";; esac