有没有简单的方法可以将命名参数传递(接收)到Shell脚本?
例如,
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中可能吗?
如果您不介意仅限于单个字母的参数名称,即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
;;
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
有一个有用的Small getopts教程,或者您可以help getopts
在shell提示符下键入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句