When writing shell scripts, reuseability is important, and key to generalising the script is designing it to accept arguments. In order to remain consistent with the behaviour of other Unix commands – using switches and values – the easiest way to implement this without reinventing the wheel on every script is to use the “getopts” command.
Sadly, getopts seems to be one of those things which is easy to forget how to use, mostly because the syntax isn’t completely intuitive.
I like to have an example on hand to refer to, and plagiarise. Here is a simple one below. It accepts a toggle argument of “-v” to render the script verbose, and a switch “-f” which takes a filename as an argument – so pretty much your standard switches. Getopts parses this argument list and sets user variables accordingly. In order to understand the example below, all you need to know is that the colon (:) passed to “getopts” indicates that a string is expected as input. As you’d expect, any deviation from the pattern returns an error.
#!/usr/bin/sh VFLAG=off FILENAME= while getopts vf: OPT do case "$OPT" in v) VFLAG=on;; f) FILENAME="$OPTARG" ;; \?) # Unknown flag echo >&; 2 "usage: $0 [ -v ] ... etc" exit 1;; esac done shift `expr $OPTIND-1` echo $* # remaining args in $*
So that’s it. Reuse getopts for clean, quick, professional and easily maintainable shell scripts.
Matt Parsons is a freelance Linux specialist who has designed, built and supported Unix and Linux systems in the finance, telecommunications and media industries.
He lives and works in London.