Using command line switches in bash scripts

I have a number of bash scripts that do useful things to lists of items, such as this:


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;;

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.

No comments: