Case statement
Running this script with:
- No option displays the specified message.
- An invalid option displays the specified message.
- A valid option loops through the options to find and display the specified message.
- A colon before the options allows custom messages for missing arguments.
- A colon after an option indicates that an argument is requited.
- Multiple valid options or options and arguments displays the specified messages for each.
- Arguments supplied for options that don’t require them will be ignored.
In this example:
- Custom messages for missing arguments are allowed.
- Options -a and -b and -c and -h are valid.
- All other options are invalid.
- Option -a does not require an argument.
- Option -b requires an argument.
- Option -c requires an argument.
- Option -h does not require an argument.
#!/bin/bash case "$1" in # Valid options: -a | -b | -c | -h) # Loop through valid options, two of which require arguments: while getopts :ab:c:h opt; do case $opt in # Valid option with missing argument: :) echo "You must use an argument with the -$OPTARG option.";; # Valid option: a) echo "You have used the -$opt option.";; # Valid option with argument: b) echo "You have used the -$opt option with the $OPTARG argument.";; # Valid option with argument: c) echo "You have used the -$opt option with the $OPTARG argument.";; # Valid option: h) echo "You have used the -$opt option to display the help text.";; esac; done; ;; # Missing option: "carview.php?tsp=") echo "You have not used an option.";; # Invalid option: *) echo "You have used the invalid $1 option.";; esac;
Obligatory Happy Ending
And they all lived happily ever after. The end.

Comment: