How do I handle switches in a shell script? Code Answer

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?


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. "$@")
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.

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji