Bashスクリプトの後に表示されるオプションは、コマンドライン引数を受け入れます。

Bashスクリプトの後に表示されるオプションは、コマンドライン引数を受け入れます。

複数のオプションのフラグと2つの必須パラメータを受け入れるbashスクリプトがあります。現在のコマンドライン呼び出しは~/script.sh -a -b arg1 arg2正しく機能しますが、呼び出しは~/script.sh arg1 arg2 -a -b認識されずに設定-aされます-b。簡単な例は次のとおりです。

#!/usr/bin/env bash
while :; do
    case $1 in
        -a)
            flag_a=true
        ;;
        -b) 
            flag_b=true
        ;;
        *) ## cause of problem: breaks the loop when the first argument is encountered
            break
    esac
    shift
done
arg_1=$1
arg_2=$2
if [ -z ${arg_1:+x} ] || [ -z ${arg_2:+x} ]; then
    echo -e "\n:-( ERROR: two arguments are required" | tee -a /dev/tty 1>&2
    exit 1
fi
flag_a=${flag_a:-false}
flag_b=${flag_b:-false}
if [ "$flag_a" = true ]; then
    echo "arg_1 is $arg_1"
fi
if [ "$flag_b" = true ]; then
    echo "arg_2 is $arg_2"
fi
if [ ! "$flag_a" = true ] && [ ! "$flag_b" = true ]; then
    echo "no options set"
fi
exit 0

必須パラメータの後にリストされているオプションのフラグを許可する方法はありますか?見つかったパラメータを何とか保存し*)てループを$*完了したら、配列に再度追加できますか?while

ベストアンサー1

おすすめ記事