Sometimes we may wish to take different paths based upon a variable matching a series of patterns. We could use a series of if and elif statements but that would soon grow to be unwieldily. Fortunately there is a case statement which can make things cleaner. It's a little hard to explain so here are some examples to illustrate:
case <variable> in <pattern 1>) <commands> ;; <pattern 2>) <other commands> ;; esac
Example 1)
#!/bin/bash # case example case $1 in start) echo starting ;; stop) echo stoping ;; restart) echo restarting ;; *) echo don\'t know ;; esac
Example 2) Regular Expression
#!/bin/bash # Print a message about disk useage. space_free=$( df -h | awk '{ print $5 }' | sort -n | tail -n 1 | sed 's/%//' ) case $space_free in [1-5]*) echo Plenty of disk space available ;; [6-7]*) echo There could be a problem in the near future ;; 8*) echo Maybe we should look at clearing out old files ;; 9*) echo We could have a serious problem on our hands soon ;; *) echo Something is not quite right here ;; esac