Parsing options in bash shell scripts

Here is the way I parse options in my bash shell scripts
# Script usage
USAGE="${0##*/}"' [options] arguments ...
This is the documentation that is printed when you call this script
with bad arguments, or -? or -help.
  -foo N    Sets the value of foo to the number N (default: 3600)
  -bar      Do not use a temporary file (default: /tmp/twpc.number)

# Options default value

# Options processing
while test "_${1#-}" != "_$1" -a "_${1//-/}" != "_";do case "$1" in
  -foo) foo="$2"; shift;;
  -bar) unset bar;;
  *) echo "$USAGE"; exit 1;
esac;shift; done; if test "_$1" = "_--";then shift; fi

# Now, $@ (or $*) contains the list of arguments with options removed
# we can post-process and check the options

  • when processing options with agruments, append as many shifts as you have arguments
  • it works even if arguments and options start with - or --
  • options must be before real arguments
  • options cannot be combined: use -i -f not -if

-- ColasNahaboo - 2008-11-30

Topic revision: r9 - 2009-01-10, ColasNahaboo
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Colas? Send feedback