2

getopts を使用しようとしている bash 関数があり、問題が発生しています。

この関数は、それ自体 ( 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]$

-sopt を 2 回 解析するのはなぜですか?

4

3 に答える 3

2

Bash 4 を実行している Ubuntu 10.4 ボックスでも、Bash 3.2.17 を実行している MacOSX ボックスでも、問題を再現できません。

シェル環境は、以前のデバッグ作業によって汚染されている可能性があります。

新しいターミナル ウィンドウで起動しようとしましたか? または、「exec bash」を使用して新しいシェルを開始し、機能を再試行してください。

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 に答える