名前付きパラメータをシェルスクリプトに渡す(受信する)簡単な方法はありますか?
例えば、
my_script -p_out '/some/path' -arg_1 '5'
内部的に次のようにmy_script.sh
受信します。
# I believe this notation does not work, but is there anything close to it?
p_out=$ARGUMENTS['p_out']
arg1=$ARGUMENTS['arg_1']
printf "The Argument p_out is %s" "$p_out"
printf "The Argument arg_1 is %s" "$arg1"
BashやZshでこれは可能ですか?
ベストアンサー1
単一文字パラメータ名(例:)に制限されていても問題ない場合は、my_script -p '/some/path' -a5
bashで組み込み機能を使用できますgetopts
。
#!/bin/bash
while getopts ":a:p:" opt; do
case $opt in
a) arg_1="$OPTARG"
;;
p) p_out="$OPTARG"
;;
\?) echo "Invalid option -$OPTARG" >&2
exit 1
;;
esac
case $OPTARG in
-*) echo "Option $opt needs a valid argument"
exit 1
;;
esac
done
printf "Argument p_out is %s\n" "$p_out"
printf "Argument arg_1 is %s\n" "$arg_1"
それからあなたはできます
$ ./my_script -p '/some/path' -a5
Argument p_out is /some/path
Argument arg_1 is 5
役に立つものがありますgetopts 小さなチュートリアルまたは、help getopts
シェルプロンプトに入力することもできます。
編集:オプションに引数がなく、後にsプログラムなどの他のオプションがある場合、ループのcase
2番目のステートメントが実行されます。while
-p
my_script -p -a5
exit