代码之家  ›  专栏  ›  技术社区  ›  ABach

分析bash中的getopts

  •  2
  • ABach  · 技术社区  · 15 年前

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

    这个 格氏大师 情况就是奇怪发生的地方。上面应该说出来 s 有一次,但我得到了:

    [user@host:git-repositories/temp]$ getch -s master
    s
    s
    [user@host:git-repositories/temp]$
    

    为什么要分析 -S 选择两次?

    3 回复  |  直到 12 年前
        1
  •  2
  •   Stefan Lasiewski    15 年前

    在运行bash 4的Ubuntu10.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
    
        2
  •  1
  •   yabt    15 年前
        3
  •  0
  •   Daniel Harms    15 年前

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

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