Shell中空格、雙引號與Word Splitting、Double quoting掃盲介紹

         在編寫shell腳本的過程中,經常遇見空格以及雙引號相關的問題,下邊詳細介紹一下相關的知識。
         從shell命令的執行過程說起,執行shell命令的本質其實就是執行一系列系統調用,簡單來說就是在執行execve(2)系統調用時將跟命令語句相關的三部分信息傳遞給它:
         1、The file to execute: This can be a binary program or a script.
         2、An array of arguments: A list of strings that tell the program what to do.
         3、An array of environment variables
        下邊舉個例子:rm myfile myotherfile 執行這條語句的過程中shell解釋器首先做的工作是分解命令語句:
            rm myfile myotherfile
                ^      ^
           [rm]
           [myfile]
           [myotherfile]
        如何分解得到以上三部分,這就是Word Splitting,說到Word Splitting就必須首先講解一下IFS(Internal Field Separator)IFS定義:which is used to determine what characters to use as word splitting delimiters,在默認情況下,IFS包括:space, tab, newline 即:($' \t\n'),上邊例子中用到的就是空格space,當然,IFS也可以自己重新設置,不過不建議這麼做,很容易帶來更多麻煩。
       根據上邊的講述,貌似很簡單,但是,簡單也蘊藏着一些很容易出錯的點,下面再來一個例子:
           rm Children of Men - Chapter 1.pdf
                ^               ^  ^       ^ ^      
          [rm]
          [Children]
          [of]
          [Men]
          [-]
          [Chapter]
          [1.pdf]
       我們原本想要乾的事是要刪除Children of Men - Chapter 1.pdf這個文件,但是shell解析後變成了刪很多個被錯誤分解的文件名,這時雙引號就派上用場了,也即:Quoting rm "Children of Men - Chapter 1.pdf" 加上雙引號能夠屏蔽空格作爲IFS功能,英文原版這樣說:Changing something from syntax into literal data,那Double quoting又是什麼呢?再上一個例子:
         var="Children of Men - Chapter 1.pdf"
         rm $var
         [rm]
         [Children]
         [of]
         [Men]
         [-]
         [Chapter]
         [1.pdf]
      如上又會出現之前的錯誤,這時我們將rm $var改成rm "$var",重新試一下結果將會是正確的,這就是Double quoting

參考文獻:
1、http://bash.cumulonim.biz/Arguments.html
2、http://bash.cumulonim.biz/WordSplitting.html
3、http://bash.cumulonim.biz/Quotes.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章