I’m writing a simple bash script that takes one optional parameter (-t ) followed by some number of additional arguments.
I was thinking getopts would be a reasonable way to achieve this, but I’m having difficulty getting the desired behavior. What I have is the following:
foo() {
baz=10
while getopts ":t:" option; do
case "$option" in
t) baz=$OPTARG ;;
esac
done
shift $((OPTIND - 1))
bar -t $baz $1 $2 $3
}
The problem is that $OPTIND does not seem to vary depending on whether the argument is present, so I don’t get the correct behavior as expected with an optional parameter (i.e., I can’t get shift to shift the right number of arguments regardless of whether the argument is there).
I want both of the following to execute correctly:
foo a b c
foo -t 5 a b c
What’s the easiest way to achieve this? I’d prefer a solution that isn’t a hack since I may want to use additional optional parameters.
The problem is that you’re never resetting
$OPTIND, so each time you callfooit examines its arguments starting after the last processed option-index. For example:The solution is to localize
$OPTINDwithinfoo, explicitly setting it to1:(You probably want to localize
$bazas well, while you’re at it.)