Parsing getopts in bash
- by ABach
I've got a bash function that I'm trying to use getopts with and am having some trouble.
The function is designed to be called by itself (getch), with an optional -s flag (getch -s), or with an optional string argument afterward (so getch master and getch -s master are both valid).
The snippet below is where my problem lies - it isn't the entire function, but it's what I'm focusing on:
getch()
{
if [ "$#" -gt 2 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Usage: $0 [-s] [branch-name]" >&2
return 1
fi
while getopts "s" opt; do
echo $opt # This line is here to test how many times we go through the loop
case $opt in
s)
squash=true
shift
;;
*)
;;
esac
done
}
The getch -s master case is where the strangeness happens. The above should spit out s once, but instead, I get this:
[user@host:git-repositories/temp]$ getch -s master
s
s
[user@host:git-repositories/temp]$
Why is it parsing the -s opt twice?