2014-12-10 58 views
1

我现在有一个bash脚本中,我已经硬编码的某些变量,而我希望能够通过传递参数来设置这些变量。传递变量bash脚本使用默认值

一个简单的例子:认为剧本example.sh在那里我有硬编码值的变量data_namesrun_this

#!/bin/bash 

data_names=("apple_picking" "iris") 
run_this="TRUE"  

#remainder of script runs things using these hard coded variables 

我想知道是否可以编辑这个脚本,以便:

  1. 我可以通过传递参数来设置data_namesrun_this的值当我运行时bash example.sh

  2. 如果没有参数传递的任何data_namesrun_this到脚本,则变量应采取默认(硬编码)的值。

+1

是的,这是可能的。你到目前为止尝试过什么,发生了什么? – Robert 2014-12-10 22:14:53

回答

2

如果你想要的东西强劲,清晰&优雅,你应该看看到getopts设置run_this

教程:http://wiki.bash-hackers.org/howto/getopts_tutorial例子:http://mywiki.wooledge.org/BashFAQ/035

我觉得是这样的:

./script --run-this=true "apple_picking" "iris" 
+1

谢谢!这是目前为止,因为它不要求输入参数的最佳选择在给定的顺序来指定/可以处理多个输入参数。 – 2014-12-11 16:39:34

+0

当然,这是建议的解决方案HTH的目标 – 2014-12-11 16:40:50

0

您可以使用:

#!/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[@]}"; 
0

另一种选择是这样的:

run_this=${1:-TRUE} 
    IFS=',' read -a data_names <<< "${2:-apple_picking,iris}" 

假设你的脚本调用,如:

./script.sh first_argument array,values,in,second,argument