More Conditions Than ELIF Likes
This lesson looks at using BASH case statements. The if statement in BASH is adequate for testing a few conditions. Adding each conditional test becomes cumbersome, though, when it needs to test more. Even with the simple example we used when looking at extending the IF statement previously can be better written as a CASE statement.
A Better Case
If we need to add many ELIF elements to an IF statement it may be better to rewrite it as a CASE statement. Using CASE statements we read in the one variable and compare its values against many conditions. This is more efficient than ELIF statements which re-evaluate at each test. We can see the script that we used in previously simplified with a CASE statement, note that a CASE statement is terminated with ESAC, case reversed.
case $1 in "directory") find /etc -maxdepth 1 -type d ;; "link") find /etc -maxdepth 1 -type l ;; "file") find /etc -maxdepth 1 -type f ;; *) echo "Usage: $0 file | directory | link " ;; esac
A Practical Case Statement
As a simple demonstration, the script works well, but I have always been keen on practical scripts and perhaps having a script that runs once a week on your servers to check for disk space could be useful. Maybe the script would only email if the percentage of space was at a certain level. We could test for different percentage levels and then run different commands based on those levels.
SPACE=$(df -h | awk '{ print $5 }' | grep -v Use | sort -n | tail -1 | cut -d % -f1 ) case $SPACE in [1-6]* | ?) MESSAGE="All is quiet." ;; [7-8]?) MESSAGE="Start thinking about cleaning out some stuff. There's a partition that is $SPACE % full." ;; 9[0-8]) MESSAGE="Better hurry with that new disk... One partition is $SPACE % full." ;; 99) MESSAGE="I'm drowning here! There's a partition at $SPACE %!" ;; *) MESSAGE="I seem to be running with an nonexistent amount of disk SPACE..." ;; esac