shell中單引號、雙引號、反引號的使用

來源:互聯網
上載者:User

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把行尾的反斜線作為續行,這種結構在分幾行輸入長命令時經常使用。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.