Code Log In

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.
Options:
  -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
foo=3600
bar=/tmp/twpc.$$

# 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

Notes:
  • 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

-- Colas Nahaboo - 2008-11-30

Topic wiki name: Code.ParsingOptionsInBash   |   Topic revision: r1 - 2009-01-10, UnknownUser - This page was cached on 2020-08-12 - 09:11.


Path: Code / ParsingOptionsInBash
This site is powered by Foswiki