2013-10-14 97 views
0

我將變量$ ARGS中的所有參數串聯起來,並將它們全部傳遞給命令onece togather,就像./test_arg.sh所做的一樣。如何將字符串參數傳遞給bash腳本中的命令?

但我發現引用字符串的參數被分割成多個。

這裏是我的測試腳本,test_arg.sh執行測試用例和arg.sh只是打印上分離式線上的每個參數。

$ cat ./test_arg.sh 
#!/bin/sh 

ARGS="$ARGS OPT_1" 
ARGS="$ARGS OPT_2" 
ARGS="$ARGS 'OPT_3 is a string with space'" 

echo "./arg.sh $ARGS" 

echo '----------------------------' 

./arg.sh $ARGS 
[ [email protected] ~/tmp ] 
$ cat ./arg.sh 
#!/bin/sh 

for var in "[email protected]" 
do 
    echo "arg -> $var" 
done 

這裏COMS結果:

$ ./test_arg.sh 
./arg.sh OPT_1 OPT_2 'OPT_3 is a string with space' 
---------------------------- 
arg -> OPT_1 
arg -> OPT_2 
arg -> 'OPT_3 
arg -> is 
arg -> a 
arg -> string 
arg -> with 
arg -> space' 

但是,如果我的命令後,把參數直接是否能夠正常工作:

$ cat test_arg.sh 
#!/bin/sh 
./arg.sh OPT_1 OPT_2 'OPT_3 is a string with space' 

[ [email protected] ~/tmp ] 
$ sh test_arg.sh 
arg -> OPT_1 
arg -> OPT_2 
arg -> OPT_3 is a string with space 

我想這個問題是這樣的bash進程報價。任何人都知道嗎?

+1

如果你真的使用'sh',你爲什麼標記這個'bash'? – devnull

+0

http://mywiki.wooledge.org/BashFAQ/050是直接點。 –

回答

0

unix shell的工作方式,您對./arg.sh $ARGS的調用不會評估「引號」。

一個可能的解決方案是使用eval "./arg.sh $ARGS"

+0

如果其中一個參數是名爲'/ tmp/im-evil/$(rm -rf/*)/ hello.txt'的文件名,那麼以這種方式使用'eval'將會是一個非常非常*餿主意。 –

相關問題