I have a number of bash scripts that do useful things to lists of items, such as this:
./install_stuff.sh 10.0.0.2 10.0.5.3
By using shift, I can have the script run through various IP addresses, for example. But I wanted more. I wanted the same command to sometimes take -t tag as an option and do something different. It turns out there's a relatively easy way to do this using the getopts builtin in bash. However, while it easily found the option (if present), it ruined the shifting feature, until I figured it out. Here's a snippet that sets TAG if -t tag is present, and then is ready to be shifted through as normal.
while getopts "t:h" OPTIONNAME; do
case "$OPTIONNAME" in
t) TAG="$OPTARG";;
[?]) help;;
esac
done
shift $(($OPTIND - 1))
At this point, you can use $1 as normal; it will be the first non-option parameter. Additional options can be specified in a similar manner.
2009-08-13
Using command line switches in bash scripts
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment