next up previous contents
Next: 變數函數與模組化寫作 Up: 簡介 Previous: shell是甚麼   Contents

執行shell script與subshell

兩種方法 喚起另一個shell來執行的scripts在scripts檔頭最前面前要加
      #! /bin/sh
第一種方法是在shell script 文字檔前指出shell scripts解讀的程式在那(也就是 我們的shell)然後把文字檔的執行權限打開,照一般執行可執行檔方式執行或者叫 一個shell來解釋文字檔test.sh。
      $ test.sh
      $ /bin/sh test.sh
      $ ( . test.sh; )
      $ exec test.sh
第二種方法是用命令''.''或者source執行。
      $ . test.sh
      $ source test.sh
      $ { test.sh; }
      $ eval '. test.sh'
差別在於一些設定只有在這個shell下的才算數,而喚起另一個shell就是另一個 不相干的世界, 也就是用第一種方法執行的script中變數的設定,不會影響到原來的shell變數。 這個相當重要。ksh沒有source這個命令,所以最好不要用source。 中括號( )表示用另一個subshell大括號,{ }表示用目前shell。例如
      $ ( VAR='testvar'; )
      $ echo $VAR

      $ { VAR='testvar'; }
      $ echo $VAR
      testvar
只有{ }內的VAR中的值被設定。其中用 . 的方法要很小心, 不要在script裡面用
      $ . test.sh arg1 arg2
因為arg1 arg2會繼承呼叫這個script的arg1 arg2來,用 . 的方式最好是要執行 的script只是一團script library不帶參數。 另外如果 . test.sh執行,test.sh離開時,呼叫. test.sh的shell也跟著離開。



Cyril Huang 2002-06-14