Shell Scripting - Part 4
Purpose of Shell Scripting - Part 4
Online Scripting Resources
If you require additional practice in creating shell scripts and using the vi text editor, run the commands in your Matrix account:
Scripting Content
Bash Shell Scripting Tips
- The case statement:
The case statement is a control-flow statement that works in a similar way as the if-elif-else statement (but is more concise). This statement presents scenerios or "cases" based on values or regular expressions (not ranges of values like if-elif-else statements). After action(s) are taken for a particular scenerio (or "case"), a break statement (;;) is used to "break-out" of the statement (and not perform other actions). A default case (*) is also used to catch exceptions.
Examples (try in shell script):
read -p "pick a door (1 or 2): " pick
case $pick in
1) echo "You win a car!" ;;
2) echo "You win a bag of dirt!" ;;
*) echo "Not a valid entry"
exit 1 ;;
esac
read -p "enter a single digit: " digit
case $digit in
[0-9]) echo "Your single digit is: $digit" ;;
*) echo "not a valid single digit"
exit 1 ;;
esac - The getopts function:
Example of getopts (try in script and run with options)
while getopts abc: name
do
case $name in
a) echo "Action for option \"a\"" ;;
b) echo "Action for option \"b\"" ;;
c) echo "Action for option \"c\""
echo Value is: $OPTARG" ;;
:) echo "Error: You need text after -c option"
exit 1 ;;
\?) echo "Error: Incorrect option"
exit 1 ;;
esac