传递变量bash脚本使用默认值
我现在有一个bash脚本中,我已经硬编码的某些变量,而我希望能够通过传递参数来设置这些变量。传递变量bash脚本使用默认值
一个简单的例子:认为剧本example.sh
在那里我有硬编码值的变量data_names
和run_this
#!/bin/bash
data_names=("apple_picking" "iris")
run_this="TRUE"
#remainder of script runs things using these hard coded variables
我想知道是否可以编辑这个脚本,以便:
我可以通过传递参数来设置
data_names
和run_this
的值当我运行时bash example.sh
如果没有参数传递的任何
data_names
和run_this
到脚本,则变量应采取默认(硬编码)的值。
如果你想要的东西强劲,清晰&优雅,你应该看看到getopts
设置run_this
教程:http://wiki.bash-hackers.org/howto/getopts_tutorial例子:http://mywiki.wooledge.org/BashFAQ/035
我觉得是这样的:
./script --run-this=true "apple_picking" "iris"
谢谢!这是目前为止,因为它不要求输入参数的最佳选择在给定的顺序来指定/可以处理多个输入参数。 – 2014-12-11 16:39:34
当然,这是建议的解决方案HTH的目标 – 2014-12-11 16:40:50
您可以使用:
#!/bin/bash
# create a BASH array using passed arguments
data_names=("[email protected]")
# if array is empty assign hard coded values
[[ ${#data_names[@]} -eq 0 ]] && data_names=("apple_picking" "iris")
# print argument array or do something else
printf "%s\n" "${data_names[@]}";
另一种选择是这样的:
run_this=${1:-TRUE}
IFS=',' read -a data_names <<< "${2:-apple_picking,iris}"
假设你的脚本调用,如:
./script.sh first_argument array,values,in,second,argument
是的,这是可能的。你到目前为止尝试过什么,发生了什么? – Robert 2014-12-10 22:14:53