Notes

Conditional Statements IF/ELIF/ELSE

Edit on GitHub


Bash Scripting

IF / ELSE

1if [ condition ]
2then
3  # do something
4else
5  # do something else
6fi

Be very particular of the whitespace around [ and ]. It is [ condition ] and not [condition]

OR

1if [ condition ]; then
2  # do something
3else
4  # do something else
5fi

where you can place then at the end of the same line as your if condition, separated by a semi-colon ;.

For example:

 1# Take user input
 2read input
 3    
 4# See if user provided twitter
 5if [ "$input" == "twitter.com" ]; then
 6  # show error
 7  echo "can not ping this!"
 8else
 9  # ping three times
10  ping -c3 ${input}
11fi

ELIF

ELIF is ELse IF.

 1# Take user input
 2read input
 3    
 4# See if user provided twitter
 5if [ $input == "twitter.com" ]; then
 6  # show error
 7  echo "can not ping this!"
 8elif [ $input == "google.com"  ]; then 
 9  echo "Why always Google? -_-"
10else
11  # ping three times
12  ping -c3 ${input}
13fi