gpt4 book ai didi

bash - 在 bash 中解析 getopts

转载 作者:行者123 更新时间:2023-12-04 06:52:45 27 4
gpt4 key购买 nike

我有一个 bash 函数,我试图将它与 getopts 一起使用,但遇到了一些麻烦。

该函数被设计为由自身调用( getch ),并带有一个可选的 -s标志( getch -s ),或者后面带有一个可选的字符串参数(所以 getch mastergetch -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选择两次?

最佳答案

在运行 Bash 4 的 Ubuntu 10.4 机器或运行 Bash 3.2.17 的 MacOSX 机器上,我也无法重现该问题。

您的 shell 环境可能会受到早期调试工作的影响。

您是否尝试从新的终端窗口开始?或者使用 'exec bash' 启动一个新的 shell,然后再次尝试该函数。

stefanl@ubuntu:~ $ 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
> }
stefanl@ubuntu:~ $ getch -s master
s

关于bash - 在 bash 中解析 getopts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2886012/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com