Option Parsing In Shell

last modified: January 22, 2006

A pattern for parsing options from the command line.

Having read ParamPattern, I think this can be done in a more general and flexible way.

I usually parse options from the command line in the following way:

# Parse this function $@
function parse_opts () 
{
        # What to do if program is called with no parameters...
        if [ $# -eq 0 ]; then
                handle_no_params # insert your own code here...
        fi

        # handle all parameters
        while [ "x$1" != "x" ]
        do
                case x$1 in
                x-v|x--version) display_version ;;
                x-h|x--help)     display_help ;;    # alternatively, use the Comments As Data pattern here...
                *) ;;                              # Just ignore this unknown option...
        esac
        shift
        done
},

# do it!
parse_opts $@

You then call parse_opts with $@ (all the argument from the command line). Note that you can easily handle different parameters in different places. It's perfectly possible to have several similar parse_opts functions handling different types of parameters, since the function works on a "copy" of $@ (you could use this in the ParamPattern scenario where you parse general options in a separate place).

The GNU getopt program is also a nice way to do it. It gives you a lot of control and flexibility. However, sometimes it's not available on the platform you're working on. The solution above relies only on shell builtins.

-- Christian Theil Have (cth @ dasfisk dot dk)


CategoryUnixShellPattern


Loading...