2016-12-31 58 views
0

我想將一組單詞作爲參數傳遞給bash腳本。看來,當我想打印參數時,只有組的第一個字是打印。將一組單詞作爲bash腳本參數傳遞

這些是我的腳本,第一個將一組單詞分配給一個變量並將該變量傳遞給另一個腳本。第二個是打印它傳遞的變量。

script.sh

#!/bin/bash 
GC='lblue, lblue, lgrey, lred, lred' 
./script2.sh $GC 

script2.sh

#!/bin/bash 
printf "$1 \n" 

這是我的腳本當前結果當我運行它

./script.sh 
lblue, 

我想腳本輸出而不是

lblue, lblue, lgrey, lred, lred 

回答

2

雙引號引起的變量保留空格 - 這是在bash的最佳實踐之一:

#!/bin/bash 
GC='lblue, lblue, lgrey, lred, lred' 
./script2.sh "$GC" 

在script2.sh:

#!/bin/bash 
printf "$1 \n" => when $GC was passed without double quotes, shell treated them as separate words and $1 was the first word 
0

你也可以傳遞陣列:

script.sh

#!/bin/bash 
a=("[email protected]") 
gc=$(IFS=, ; printf "${a[*]}"| sed 's/, */, /g') 
printf "${gc[*]} \n" 

輸入

gc=(red green blue) 
./script.sh ${gc[*]} 

輸出將是:

red, green, blue