2010-09-20 212 views
9

比方說,我有一個非常簡單的shell腳本 '富':

#!/bin/sh 
    echo [email protected] 

如果我調用它像這樣:

foo 1 2 3 

它高興地打印:

1 2 3 

然而,讓我們說我的一個論點是雙引號括起來幷包含空格:

foo 1 "this arg has whitespace" 3 

富高興地打印:

1 this arg has whitespace 3 

雙引號被剝奪!我知道貝殼認爲它幫了我一個忙,但是......我希望得到原始版本的論證,不受殼層解釋的影響。有沒有辦法做到這一點?

回答

1

您需要引用報價:

foo 1 "\"this arg has whitespace\"" 3 

或(更簡單)

foo 1 '"this arg has whitespace"' 3 

你需要引用的雙引號,以確保在解析時shell不刪除它們單詞參數。

6

首先,您可能需要引用版本[email protected],即"[email protected]"。爲了感受不同,嘗試在字符串中放置多個空格。

其次,引號是shell的語法元素 - 它不會幫你一個忙。爲了保護它們,你需要逃避它們。例子:

foo 1 "\"this arg has whitespace\"" 3 

foo 1 '"this arg has whitespace"' 3 
2

雙引號$ @:

#!/bin/sh 
for ARG in "[email protected]" 
do 
    echo $ARG 
done 

然後:

foo 1 "this arg has whitespace" 3 

會給你:

1 
this arg has whitespace 
3 
+0

然後我們可以使用'IFS'來避免在其他答案中引用地獄,如果有人想用這些參數做任何有用的事情.... – 2017-08-02 00:01:16

2

讓我們假設你是在一個更嚴格的一套並且你不能改變你的命令行,然後make它通過逃避雙引號更「友好」。例如:

example_script.sh argument_without_quotes "argument with quotes i cannot escape" 

首先考慮的是你的腳本中如果參數是帶或不帶引號過去了,你看不出來,因爲外殼剝離它們。

所以你能做的重建雙引號包含空格

這個例子重建整個命令行,有空格

#!/bin/sh 
#initialize the variable that will contain the whole argument string 
argList="" 
#iterate on each argument 
for arg in "[email protected]" 
do 
    #if an argument contains a white space, enclose it in double quotes and append to the list 
    #otherwise simply append the argument to the list 
    if echo $arg | grep -q " "; then 
    argList="$argList \"$arg\"" 
    else 
    argList="$argList $arg" 
    fi 
done 

#remove a possible trailing space at the beginning of the list 
argList=$(echo $argList | sed 's/^ *//') 

#pass your argument list WITH QUOTES 
echo "my_executable" $argList 
#my_executable $argList 

注意這一限制雙引號的論點論據。如果你運行這個例子

你會得到這個輸出

my_executable "argument with spaces" argument_without_spaces argument_doublequoted_but_without_spaces 

注意最後一個參數:因爲它沒有空格,它並沒有被用雙引號括再次,但是這不應該成爲一個問題。

2

我會做的是引用所有收到的空格,可能會幫助你的情況。

for x in "${@}" ; do 
    # try to figure out if quoting was required for the $x 
    if [[ "$x" != "${x%[[:space:]]*}" ]]; then 
     x="\""$x"\"" 
    fi 
    echo $x 
    _args=$_args" "$x 
done 

echo "All Cmd Args are: $_args" 
相關問題