變數和命令替換的雙引號

變數替換隻應在雙引號內使用。

calculation='2 * 3'
echo "$calculation"         # prints 2 * 3
echo $calculation           # prints 2, the list of files in the current directory, and 3
echo "$(($calculation))"    # prints 6

在雙引號之外,$varvar 的值,將其拆分為以空格分隔的部分,並將每個部分解釋為 glob(萬用字元)模式。除非你想要這種行為,否則總是將 $var 放在雙引號內:$var

這同樣適用於命令替換:$(mycommand)mycommand 的輸出,$(mycommand) 是輸出上 split + glob 的結果。

echo "$var"             # good
echo "$(mycommand)"     # good 
another=$var            # also works, assignment is implicitly double-quoted
make -D THING=$var      # BAD! This is not a bash assignment.
make -D THING="$var"    # good
make -D "THING=$var"    # also good

命令替換得到他們自己的引用上下文。編寫任意巢狀替換很容易,因為解析器將跟蹤巢狀深度,而不是貪婪地搜尋第一個 " 字元。但是,StackOverflow 語法高亮顯示器解析了這個錯誤。例如:

echo "formatted text: $(printf "a + b = %04d" "${c}")" # “formatted text: a + b = 0000”

命令替換的變數引數也應該在擴充套件中加雙引號:

echo "$(mycommand "$arg1" "$arg2")"