BASH Case Statement

Download PDF

More Conditions using the BASH Case Statement

BASH case statementYes, we can create even more conditions when we make use of the BASH Case Statement in our scripts. Even though we could do the same using many elif condition tests a case statement is easier to read and more efficient. We like easy to read and your computers like more efficient.


If we want to refactor the elif script that we created before we can write it using the fallowing case statement.

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

Some things to note here:

  • We open the code block with case and close it with esac
  • We use the double semi-colon ;; to end each condition action
  • We can use just the closing parenthesis around each test such as “directory”) or we can use the open and close pair as in (“directory”).

Here we are still using a simple example but or course this is something that you can play with and build around your own needs. Like everything the more you start using the code the easier it becomes.

Even though it does work well as a simple demonstration for the bash case statement  I  have always been keen on practical scripts. Scripts that you can use and make use off. So perhaps we can look at a tittle more complex script. This script could 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.

We first populate the variable called SPACE which will have the space used value from the command df.  Upto 69% we are not worried, then we move up to 89%, then 98% before 99%. Obviously the more space that is in use the more concerned we become.

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

You can watch the video here:

My Book on Shell Scripting is available from good book shops and the publisher Packt.

shellscripting