shell中單引號、雙引號、反引號的使用 在編寫shell指令碼時,會經常地使用到單引號、雙引號、反引號這些特殊的符號。它們在shell中有著不同的作用,但容易被誤用和引起混亂。簡單總結一下三者的使用和區別。 單引號它關閉shell中所有的特殊符號使用和解釋,即單引號間的內容全部以一般字元的含義進行文本使用和解釋,不管是特殊字元 $ ,還是逸出字元之類的。例子: 1~$ a=12;test='this is a $a \$ `date`';echo $test2this is a $a \$ `date`雙引號它關閉shell中大部分的特殊符號,但是某些保留,比如 $ ,逸出字元 \(不包括\n,\t之類),反引號字元,單引號字元在雙引號中時作為一般字元,不具有上面的功能作用。例子: 01~$ a=12;test="this is a $a \b `date`";echo $test02this is a 12 \b Thu Mar 21 15:24:45 HKT 201303 04~$ a=12;test="'this is a $a \b `date`'";echo $test05'this is a 12 \b Thu Mar 21 15:32:09 HKT 2013'06 07~$ a=12;test="this is a $a \n `date`";echo $test08this is a 12 \n Thu Mar 21 15:40:09 HKT 201309 10~$ a=12;test="this is a $a \$ `date`";echo $test11this is a 12 $ Thu Mar 21 15:40:38 HKT 2013單引號、雙引號用於把帶有空格的字串賦值給變數,如果沒有單引號或雙引號,shell會把空格後的字串解釋為命令,即把空格作為變數賦值的結束。 1~$ a=13;test1=this is a $a \b `date`; echo $test12is: command not found特別注意:在shell指令碼中進行變數的賦值時,變數名、等號和變數值之間不能有空格,否則就是上面一樣的錯誤。 反引號它的作用是命令替換,將其中的字串當成shell命令執行,返回命令的執行結果,見上面的例子。反引號包括的字串必須是能執行的命令,否則會出錯。例子: 1~$ a=12;test=`this is a $a \b `date``;echo $test2No command 'this' found, did you mean:3 Command 'thin' from package 'thin' (universe)4this: command not found5date符號$( )的作用和反引號的一樣,都是命令替換: 1~$ echo $(date)2Thu Mar 21 15:54:15 HKT 2013反斜線反斜線一般用作逸出字元,如果echo要讓逸出字元發生作用,就要使用-e選項,且包含逸出字元的字串要使用雙引號 1~$ echo "this is a \n test"2this is a \n test3~$ echo -e "this is a \n test"4this is a5 test反斜線的另一種作用,就是當反斜線用於一行的最後一個字元時,shell把行尾的反斜線作為續行,這種結構在分幾行輸入長命令時經常使用。