Here is the video version, if you prefer it:
Today let’s talk about the case statement. case statement is used to replace a lot of elif statements. Here is our entire script with the same functionality it had before, rewritten using a case statement:
#!/bin/bash
case $1 in
'Hello')
echo 'Hello back to you!'
;;
'Hi')
echo 'Hi!'
;;
*)
echo 'You are rude.'
;;
esac
Here is how the case statement works:
- You tell case which argument you are testing (more specifically, pattern matching) – we are testing the argument passed to the script in the first position (
$1) casegoes through the list of patterns (each pattern ends in a)) and if it finds a matching pattern, the code between the)and the;;is executed and then it skips toesacesacdenotes the end of the case statement
The case statement does not evaluate any exit codes, it just matches patterns.
Here are some things to note: (Ward, 2014)
- multiple strings can be matched with | – if I put ‘Hi!’|’Hi’ I would match both “Hi!” and “Hi” and that line would look like
'Hi!'| ‘Hi’) *matches a case which is unmatched by any other case
Hope you found this useful!
References
Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 261-262
Leave a Reply