建立及執行 shell script

shell script 是一種包含一或多個指令的檔案。shell script 提供一個簡單的方法,讓您執行冗長單調的指令、大量或複雜的指令順序,以及例行作業。當您輸入 shell script 檔的名稱時,系統會執行檔案所包含的指令序列。

您可以使用文字編輯器來建立 shell script。您的 script 可包含作業系統指令與 shell 內建指令。

下列步驟是撰寫 shell script 的一般指引:
  1. 使用文字編輯器,建立及儲存檔案。您可以將 shell 與作業系統指令的任何組合併入 shell script 檔中。依照慣例,尚未設定給許多使用者使用的 shell script,會儲存於 $HOME/bin 目錄中。
    註: 作業系統不支援 Shell Script 內的 setuidsetgid 子常式。
  2. 使用 chmod 指令,只允許擁有者執行檔案。例如,如果您的檔案名稱是 script1,請鍵入:
    chmod u=rwx script1
  3. 在指令行輸入 script 名稱來執行 shell script。若要執行 script1 shell script,請鍵入:
    script1
    註: 如果指令行上將 shell 指令(kshbshcsh)置於 shell script 檔名之前,則不需要將 shell script 建立成可執行檔,也可以執行它。例如,若要在 Korn shell 中執行非執行檔 script1,請鍵入下列指令:
    ksh script1