How do I handle switches in a shell script?

Are there some built-in tools that will recognize -x and --xxxx as switches, and not arguments, or do you have to go through all the input variables, test for dashes, and then parse the arguments thereafter?

Answer

Use getopts.

It is fairly portable as it is in the POSIX spec. Unfortunately it doesn’t support long options.

See also this getopts tutorial courtesy of the bash-hackers wiki and this question from stackoverflow.

If you only need short options, typical usage pattern for getopts (using non-silent error reporting) is:

# process arguments "$1", "$2", ... (i.e. "[email protected]")
while getopts "ab:" opt; do
    case $opt in
    a) aflag=true ;; # Handle -a
    b) barg=$OPTARG ;; # Handle -b argument
    ?) ;; # Handle error: unknown option or missing required argument.
    esac
done

Leave a Reply

Your email address will not be published. Required fields are marked *