This is my entire script in its simplest form.
#!/bin/bash
src=""
targ=${PWD}
while getopts "s:t:" opt; do
case $opt in
s)
src=$OPTARG
;;
t)
targ=$OPTARG
;;
esac
shift $((OPTIND-1))
done
echo "Source: $src"
echo "Target: $targ"
I run this script as getopts_test -s a -t b
However, it always prints the pwd
in front of the Target:
and never b
What am I missing here?
The reason for why b
is never printed is that the shift
within the loop moves the processed options away after the first iteration, i.e. after a
has been printed. Use of shift $((OPTIND-1))
is intended to access the possible given variadic parameters. Naturally, once you remove shift
, targ
gets reassigned to b
, and ${PWD}
is no longer included in it since you don't have concatenation of the strings (targ
and the option of -t
) anywhere.