パラメータが1つだけ設定されている場合のbashパラメータの変更

パラメータが1つだけ設定されている場合のbashパラメータの変更

スクリプト標準としてgetopt魔法、スクリプトを呼び出すことができます。

batman-connect -c ffki

ダッシュなしで単一のオプションでこのスクリプトを呼び出すオプションを追加するにはどうすればよいですか?

batman-connect ffki

-cしたがって、この唯一のオプションを?の2番目の引数として解釈します。

~によるとこの回答私は試した:

if [ $@ = "ffki" ]; then
  set -- "-c $@"
fi

しかし、これは私の行のためにエラーが発生すると思います。スクリプト次に、もう一度変更してください。

# Execute getopt on the arguments passed to this program, identified by the special character $@
PARSED_OPTIONS=$(getopt -n "$0"  -o hsrvVi:c: --long "help,start,restart,stop,verbose,vv,version,interface:,community:"  -- "$@")

スクリプト全体を並べ替えるのが好きではありません。最初のパラメータを「-c」に設定し、2番目のパラメータを「ffki」に設定する簡単な1行はありますか?

ベストアンサー1

次のようなことができます

if [ $# = 1 ]; then
    # do whatever you'd do when there is only one argument
else
    # do the getopt bits
fi
# do what you'd do in either case

-cがサポートする唯一のスイッチである場合は、getoptは必要ありません。次のように実行できます。

#!/bin/bash

usage() {
    echo "Usage: $0 [ -c ] arg" >&2
    exit 1
}

if [ $# = 2 ]; then
    if [ $1 = "-c" ]; then
        shift
        c_switch_value="$1"
    else
        usage
    fi
elif [ $# = 1 ]; then
    c_switch_value="$1"
else
    usage
fi

これがより読みやすいかどうかは議論の余地があります。

おすすめ記事