解析 bash 中的 getopt
我有一个 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 两次?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在运行 Bash 4 的 Ubuntu 10.4 机器或运行 Bash 3.2.17 的 MacOSX 机器上,我也无法重现该问题。
您的 shell 环境可能会受到早期调试工作的污染。
您是否尝试过从新的终端窗口开始?或者使用“exec bash”启动一个新的 shell,然后再次尝试该功能。
I can't reproduce the problem either, on an Ubuntu 10.4 box running Bash 4, or my MacOSX box running Bash 3.2.17.
Your shell environment might be tainted by earlier debugging efforts.
Have you tried to start with a new terminal window? Or start a new shell with 'exec bash' and try the function again.
这是一种不使用 getopts 的方法:
http:// /bsdpants.blogspot.com/2007/02/option-ize-your-shell-scripts.html
Here's a way to do it without getopts:
http://bsdpants.blogspot.com/2007/02/option-ize-your-shell-scripts.html
尝试在您编写的函数之外解析选项。今天下午我又考虑了一下这个问题。在解析函数中的选项(而不是仅在脚本主体中)时,我很难让它正常工作。
不然我真的不知道该告诉你什么。
Try parsing the options outside of a function you've written. I toyed around with this a little bit more this afternoon. I had a hard time having it work properly when parsing the options in a function as opposed to just in the main body of the script.
Otherwise, I don't really know what to tell you.