Getopts option processing, Is it possible to add a non hyphenated [FILE]?

6,360

Solution 1

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
do
    case "$option" in
        x) echo "x";;
        z) echo "z";;
        o) echo "o=$OPTARG";;
    esac
done
shift $(($OPTIND-1))
FILE="$1"

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

Solution 2

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
  NONOPTION=$1
  shift
fi
ARGS=$(getopt ...)
Share:
6,360

Related videos on Youtube

J. M. Becker
Author by

J. M. Becker

Updated on September 18, 2022

Comments

  • J. M. Becker
    J. M. Becker over 1 year

    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
    
  • angus
    angus over 12 years
    Although my answer was about getopt (not getopts), I'll leave it because the part about extracting the first parameter is still valid.
  • J. M. Becker
    J. M. Becker over 12 years
    I'm going to test this one out, looks like a good implementation.