1 [me@linuxbox ~]$ echo this is a test 2 this is a test
shell 会对echo进行单词分割(word splitting)去除多余的空白。
1 [me@linuxbox ~]$ echo The total is $100.00 2 The total is 00.00
因为$1是一个未定义的变量,所以参数扩展会将$1替换为空字符串。
引用的目的就是由选择性的避免不想要的扩展。
一、双引号(Double Quotes)
将text放在双引号内时,所有特殊字符的特殊含义都将消失。但是字符'$','\','‘反引号’'除外,这就意味着单词分割、路径名扩展、波浪线扩展和花括号扩展都将失效,但是参数扩展、算术扩展、和命令替换仍将生效。
1 [me@linuxbox ~]$ ls -l two words.txt 2 ls: cannot access two: No such file or directory 3 ls: cannot access words.txt: No such file or directory
单词分割功能会将two words.txt分割成two 和word.txt两个部分。使用双引号就可以避免这种现象出现
1 [me@linuxbox ~]$ ls -l "two words.txt" 2 -rw-rw-r-- 1 me me 18 2016-02-20 13:03 two words.txt
记住:参数扩展、算术扩展、命令替换在双引号内仍然有效。
1 [me@linuxbox ~]$ echo "$USER $((2+2)) $(cal)" 2 me 4 February 2019 3 Su Mo Tu We Th Fr Sa
二、单引号(Single Quotes)
如果我们想抑制所有扩展,那么使用单引号。
1 [me@linuxbox ~]$ echo text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER 2 text /home/me/ls-output.txt a b foo 4 me 3 [me@linuxbox ~]$ echo "text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER" 4 text ~/*.txt {a,b} foo 4 me 5 [me@linuxbox ~]$ echo 'text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER' 6 text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER
三、转义字符(Escaping Characters)
通常使用转义字符(backslash)放在双引号中有选择性的来进行扩展。
1 [me@linuxbox ~]$ echo "The balance for user $USER is: \$5.00" 2 The balance for user me is: $5.00