Bash Conditions: if and case
Conditions let a script choose what to do, for example only creating a folder if it does not exist yet.
The if Statement
Example
marks=72
if [ "$marks" -ge 50 ]; then
echo "Pass"
else
echo "Fail"
fiPass
- The condition goes inside
[ ], with a space after[and before]. thenstarts the code to run, andfi(if backwards) ends the block.
elif
Example
temp=38
if [ "$temp" -gt 40 ]; then
echo "Extreme heat warning"
elif [ "$temp" -gt 30 ]; then
echo "Hot day, drink water"
else
echo "Pleasant weather"
fiHot day, drink water
Comparing Numbers
Bash uses letters, not symbols, to compare numbers inside [ ]:
| Operator | Meaning |
|---|---|
-eq | equal |
-ne | not equal |
-gt | greater than |
-lt | less than |
-ge | greater than or equal |
-le | less than or equal |
You can also use (( )) for number tests with normal symbols: if (( marks >= 50 )); then.
Comparing Strings
| Test | True when |
|---|---|
[ "$a" = "$b" ] | the strings are the same |
[ "$a" != "$b" ] | the strings are different |
[ -z "$a" ] | the string is empty |
[ -n "$a" ] | the string is not empty |
Example
city="Karachi"
answer=""
if [ "$city" = "Karachi" ]; then
echo "Welcome to the City of Lights"
fi
if [ -z "$answer" ]; then
echo "You did not type anything"
fiWelcome to the City of Lights You did not type anything
Always put variables inside double quotes in tests. If a variable is empty and has no quotes, [ $answer = "yes" ] becomes [ = "yes" ] and Bash shows an error.
Testing Files
| Test | True when |
|---|---|
-e path | the file or folder exists |
-f path | it is a regular file |
-d path | it is a folder |
-r path | you can read it |
-s path | the file is not empty |
Example
folder="backups"
if [ ! -d "$folder" ]; then
mkdir "$folder"
echo "Created $folder"
else
echo "$folder already exists"
fiThe first time you run this it prints Created backups. The next time it prints backups already exists. The ! means "not".
Combining Conditions and [[ ]]
Bash also has [[ ]], a safer and more powerful test. Inside it you can join conditions with && (and) and || (or), and use * patterns:
Example
age=22
city="Lahore"
if [[ $age -ge 18 && $city == "Lahore" ]]; then
echo "Adult from Lahore"
fi
file="photo.jpg"
if [[ $file == *.jpg ]]; then
echo "This is a JPG image"
fiAdult from Lahore This is a JPG image
case
case compares one value against several patterns. It is cleaner than a long elif chain.
Example
day="Sat"
case "$day" in
Mon|Tue|Wed|Thu)
echo "Class day"
;;
Fri)
echo "Short day"
;;
Sat|Sun)
echo "Weekend"
;;
*)
echo "Unknown day"
;;
esacWeekend
Each pattern ends with ), each block ends with ;;, and *) catches anything else. esac (case backwards) closes it.
Exercise
Exercise
Which test checks whether the number in $n is greater than 10?
