2011-07-14 94 views

回答

312

單引號不會內插任何內容,但雙引號(例如變量,反引號,某些\轉義等等)。

[email protected]:~# echo "$(echo "upg")" 
upg 
[email protected]:~# echo '$(echo "upg")' 
$(echo "upg") 

的擊手冊有這樣說:

3.1.2.2 Single Quotes

在單引號圍字符(')保留了引號內的每個字符的文本值。單引號之間可能不會出現單引號,即使前面加了反斜線。

3.1.2.3 Double Quotes

圍護字符在雙引號(")保留了引號中的所有字符的字面意義,與$`\例外,而且,當歷史擴充被啓用,!。字符$`在雙引號內保留其特殊含義(請參見Shell Expansions)。只有在跟隨以下字符之一時,反斜槓纔會保留其特殊含義:$,`,",\或換行符。在雙引號內,刪除後跟其中一個字符的反斜槓。沒有特殊含義的字符之前的反斜槓未作修改。雙引號可以用雙引號括起來,前面加一個反斜槓。如果啓用,將會執行歷史擴展,除非出現在雙引號中的!使用反斜槓進行轉義。 !前面的反斜槓不會被刪除。

特殊參數*@在雙引號中有特殊含義(請參見Shell Parameter Expansion)。

167

如果你指的是當你呼應的東西會發生什麼,單引號將逐字呼應你有什麼他們之間,而雙引號將它們與輸出之間的評估變量的變量的值。

例如,這

#!/bin/sh 
MYVAR=sometext 
echo "double quotes gives you $MYVAR" 
echo 'single quotes gives you $MYVAR' 

會給這樣的:

double quotes gives you sometext 
single quotes gives you $MYVAR 
87

accepted answer是巨大的。我正在製作一張有助於快速理解該主題的表格。解釋涉及一個簡單的變量a以及索引數組arr

如果我們設置

a=apple  # a simple variable 
arr=(apple) # an array with a single element 

然後echo在第二列中的表達,我們會得到在第三列中示出的結果/行爲。第四欄解釋了行爲。

# | Expression | Result  | Comments 
---+-------------+-------------+-------------------------------------------------------------------- 
1 | "$a"  | apple  | variables are expanded inside "" 
2 | '$a'  | $a   | variables are not expanded inside '' 
3 | "'$a'"  | 'apple'  | '' has no special meaning inside "" 
4 | '"$a"'  | "$a"  | "" is treated literally inside '' 
5 | '\''  | **invalid** | can not escape a ' within ''; use "'" or $'\'' (ANSI-C quoting) 
6 | "red$arocks"| red   | $arocks does not expand $a; use ${a}rocks to preserve $a 
7 | "redapple$" | redapple$ | $ followed by no variable name evaluates to $ 
8 | '\"'  | \"   | \ has no special meaning inside '' 
9 | "\'"  | '   | \' is interpreted inside "" 
10 | "\""  | "   | \" is interpreted inside "" 
11 | "*"   | *   | glob does not work inside "" or '' 
12 | "\t\n"  | \t\n  | \t and \n have no special meaning inside "" or ''; use ANSI-C quoting 
13 | "`echo hi`" | hi   | `` and $() are evaluated inside "" 
14 | '`echo hi`' | `echo hi` | `` and $() are not evaluated inside '' 
15 | '${arr[0]}' | ${arr[0]} | array access not possible inside '' 
16 | "${arr[0]}" | apple  | array access works inside "" 
17 | $'$a\''  | $a'   | single quotes can be escaped inside ANSI-C quoting 
18 | '!cmd'  | !cmd  | history expansion character '!' is ignored inside single quotes 
19 | "!cmd"  | cmd args | expands to the most recent command matching "cmd" 
---+-------------+-------------+-------------------------------------------------------------------- 

參見:

+2

該表是一個答案,在[StackOverflow的許多問題(https://stackoverflow.com) 。 – C0deDaedalus

+1

最後接受的答案說'特殊參數*和@在雙引號中有特殊含義,那麼怎麼來''*''得到'*'? –

相關問題