
The case statement is mostly used for initiation scripts, where a script is called with a start, stop, or (sometimes) restart option. There are of course many other uses.
Here is a simple case statement used to create a weather html page. A little over simplified but you’ll get the idea.
case "$1" in 'sun') echo "<html><body>Glorious sunshine today</body></html>" > forecast.html ;; 'cloud') echo "<html><body>It will be cloudy today</body></html>" > forecast.html ;; 'rain') echo "<html><body>Expect rain today</body></html>" > forecast.html ;; *) echo "<html><body>Unknown weather</body></html>" > forecast.html ;; esac
If the above example is written to a file called "forecast" we can create a weather forecast page like this:
bash$ sh forecast sun
Which will create a file called "forecast.html":
<html><body>Glorious sunshine today</body></html>
Let’s look at the individual parts of the Case statement
case "$1" in
This part tells the shell that we're using a case statement, and that the value we are
searching for is "$1". $1 means the first argument to the script, so if we call the script like this:
bash$ sh forecast rain
$1 will be set to "rain".
'rain')
The command shell searches through the case statement until it finds a match for our "rain". When it finds it, it runs the code within that branch of the statement. If it can't find a match, it runs the code in the *) branch.
;;
This determines the end of that branch of the Case statement.
esac
This determines the end of the Case statement.