2

我有一个 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]$

为什么它解析-sopt 两次?

4

3 回答 3

2

我也无法在运行 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
于 2010-05-21T23:40:36.253 回答
1

这是一种无需 getopts 的方法:

http://bsdpants.blogspot.com/2007/02/option-ize-your-shell-scripts.html

于 2010-05-22T08:13:36.793 回答
0

尝试在您编写的函数之外解析选项。今天下午我又玩弄了一点。在解析函数中的选项而不是仅在脚本主体中时,我很难让它正常工作。

否则,我真的不知道该告诉你什么。

于 2010-05-22T06:53:54.033 回答