Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using getopts for all of my scripts that require advanced option parsing, and It's worked great with dash. I'm familiar with the standard basic getopts usage, consisting of [-x] and [-x OPTION].

Is it possible to parse options like this?

 dash_script.sh FILE -x -z -o OPTION
 ## Or the inverse?
 dash_script.sh -x -z -o OPTION FILE
share|improve this question
up vote 3 down vote accepted

Script arguments usually come after options. Take a look at any other commands such as cp or ls and you will see that this is the case.

So, to handle:

dash_script.sh -x -z -o OPTION FILE

you can use getopts as shown below:

while getopts xzo: option
    case "$option" in
        x) echo "x";;
        z) echo "z";;
        o) echo "o=$OPTARG";;
shift $(($OPTIND-1))

After processing the options, getopts sets $OPTIND to the index of the first non-option argument which in this case is FILE.

share|improve this answer
I'm going to test this one out, looks like a good implementation. – TechZilla Jan 25 '12 at 2:51
This is perfect, exactly how I would want the options to go! Thanks for all your help! – TechZilla Jan 26 '12 at 1:59

Getopt will rearrange the parameters and put all non option parameters at the end, after --:

$ getopt -o a: -- nonoption-begin -a x nonoption-middle -a b nonoption-end
-a 'x' -a 'b' -- 'nonoption-begin' 'nonoption-middle' 'nonoption-end'

If you really need know that a nonoption parameter is at the beginning, you can check whether $1 is an option, and if it isn't extract it, before you call getopt:

if [ ${1#-} = $1 ]; then
ARGS=$(getopt ...)
share|improve this answer
Although my answer was about getopt (not getopts), I'll leave it because the part about extracting the first parameter is still valid. – angus Jan 24 '12 at 9:44

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.