Bash – How to shift arguments while arguments start with –

bashshell-script

Say I have a bash function, which is supposed to remove all arguments that start with "-" until it gets to an argument that does not start with "-".

gmx(){

  local options=( );

  while [ "${1:0:1}" == "-"  ]; do
    options+=("${1}")
    shift 1;
  done

  echo "first legit arg: $1"
  "$@" # omg will be executed here, like `omg --rolo`
}

gmx -a -f -c omg --rolo

this seems to work, but I am wondering if this is a good generic solution to always get 'omg' to be the first "legit" argument. Are there any edge cases that might fail?

In other words -a, -f, -c are all arguments to gmx. Whereas omg and everything that follows, will be run in a child process.

Best Answer

The official and best way is t use the getopts builtin to parse the command line options.

See the man page for more information.

A note may be important: bash does not support long options.

If you like scripts to deal with long options, you have two shells that support them: ksh93 and bosh. Both shells support long options the way they are supported by the getopt(3) function in libc on Solaris. See the bosh man page (currently starting at page 43:

http://schilytools.sourceforge.net/man/man1/bosh.1.html

getopts "f:(file)(input-file)o:(output-file)" OPT

supports e.g an option -f with an argument and that option has a long option alias --file and a second alias for this option --input-file

ksh93 supports this as well, even though it is not documented in the ksh93 man page.