I always wondered how scripts passed variables beginning with a '-', i.e 'foo.sh -q', or 'tar -zxfv' and so on.
I knew that '$1' in bash takes the first extra variable sent at the shell, but that can be any sort of word, not specifically a '-' parameter. Does that make sense?
Anyway, it turns out you can use this neat getopts function like so, with a case statement. This way you can also output a 'usage' mini-manual when a variable that is unrecognised, is passed:
usage() { cat << EOF usage: $0 -option Use this script to rsync this to that :) OPTIONS: -v Be verbose, see what is transferring -q Be quiet, hide transfer info except errors EOF } while getopts ":vq" optname do case $optname in v) rsync -aHPv /path/to/dir remote:/path/to/ ;; q) rsync -aHPq /path/to/dir remote:/path/to/ ;; ?) usage exit ;; esac done
The ':' at the start of the getopts string sets '?' as parameter if it is unrecognised. You then use '?)' in the case statement to catch these erroneous paramaters (if I've understood all this correctly)
A much more concise explanation is offered here.
- diveli's blog
- 288 reads