2014-12-10 54 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