Conditionals

Two main types of conditionals:

  • if
    • note, terminated by fi
  • case
    • note, terminated by esac

Also a pseudo Ternary using && and ||

  • command && next command || or this command

 

if conditionals

Basic if test construction:

if [ condition ]
then
    command
fi

if, then, else construction

if [ condition ]
then
    command
else
    command
fi

if, then, elif construction

if [ condition ]
then
    command
elif [ condition ]
then
    command

else

    command
fi

 

#!/bin/bash
myvar=500

echo "\$myvar = " $myvar
if (( $myvar < 666 )); then
	echo "$myvar is less than 666"
fi 

if (( $myvar < 333 )); then
	echo "$myvar is less than 333"
else 
	echo "$myvar is not less than 333"
fi

if (( $myvar < 333 )); then
	echo "$myvar is less than 333"
elif (( $myvar < 999 )); then
	echo "$myvar is less than 999"
else 
	echo "$myvar is greater than 666"
fi

 

 

Case conditionals

 

Case tests several conditions at a time, carrying out the command of the first condition met. If no condition is met, the default case will be carried out as indicated by the final *)

#!/bin/bash

rndnum=$(( ( RANDOM % 10 )  + 1 ))

# use case statement to make decision for favourite colour
case $rndnum in
	1) echo "Bash generated 1";;
	2) echo "Bash generated 2";;
	3) echo "Bash generated 3";;
	4) echo "Bash generated 4";;
	5) echo "Bash generated 5";;
	6) echo "Bash generated 6";;
	7) echo "Bash generated 7";;
	8) echo "Bash generated 8";;
	9) echo "Bash generated 9";;
	*) echo "Bash generated 10";;
esac

echo; echo "Hit a key, then hit return."
read Keypress

case "$Keypress" in
  [[:lower:]]   ) echo "Lowercase letter";;
  [[:upper:]]   ) echo "Uppercase letter";;
  [0-9]         ) echo "Digit";;
  *             ) echo "Punctuation, whitespace, or other";;
esac

today="$(date +'%A')"
case $today in
	Monday) echo "Today is Monday";;
	Tuesday) echo "Today is Tuesday";;
	Wednesday) echo "Today is Wednesday";;
	Thursday) echo "Today is Thursday";;
	Friday) echo "Today is Friday";;
	Saturday) echo "Today is Saturday";;
	*) echo "Today must be Sunday";;
esac

 

 

Pseudo Ternary conditionals

The ternary conditional can be emulated using a one liner with && and || replacing normal ? and :

#!/bin/bash
[[ TRUE ]] && echo "Test exited 0 successfully" || echo "Test failed (i.e. exited non-zero) unsuccessfully"
[[ TRUE = FALSE ]] && echo "Test exited 0 successfully" || echo "Test failed (i.e. exited non-zero) unsuccessfully"