我有一个 bash 函数,我正在尝试使用 getopts 并且遇到了一些麻烦。
该函数被设计为由自身调用(getch
),带有可选-s
标志(getch -s
),或者之后带有可选的字符串参数(因此getch master
和getch -s master
都是有效的)。
下面的片段是我的问题所在 - 它不是整个功能,但它是我关注的内容:
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
}
getch -s master
案例就是奇怪发生的地方。上面应该吐出s
一次,但相反,我得到了这个:
[user@host:git-repositories/temp]$ getch -s master
s
s
[user@host:git-repositories/temp]$
为什么它解析-s
opt 两次?