Skip to content

Latest commit

 

History

History
76 lines (41 loc) · 3.17 KB

ch2-1.md

File metadata and controls

76 lines (41 loc) · 3.17 KB

2.1. Invoking the script

第二章第一節 - 執行腳本

Having written the script, you can invoke it by sh scriptname, [1] or alternatively bash scriptname.

要執行腳本,我們可以使用 「sh 腳本檔名」 或「bash 腳本檔名」來執行。

(Not recommended is using sh <scriptname, since this effectively disables reading from stdin within the script.)

(不建議使用 「sh <腳本檔名」執行腳本,因為會無法讀取stdin輸入的值。)

Much more convenient is to make the script itself directly executable with a chmod.

更方便、直接的執行方法就是用chmod指令讓腳本變成可執行。

Either: chmod 555 scriptname (gives everyone read/execute permission) [2]

chmod 555 scriptname (給所有使用者 讀/執行 的權限) [2]

or

chmod +rx scriptname (gives everyone read/execute permission)

chmod +rx scriptname (給所有使用者 讀/執行 的權限)

chmod u+rx scriptname (gives only the script owner read/execute permission)

chmod u+rx scriptname (只給腳本擁有者 讀/執行 的權限)

Having made the script executable, you may now test it by ./scriptname. [3]

想測試腳本是否是可執行的嗎?執行./scriptname測試看看。[3]

If it begins with a "sha-bang" line, invoking the script calls the correct command interpreter to run it.

若腳本的開頭有「sha-bang」這一行,則會呼叫正確的指令解譯器來運行腳本。

As a final step, after testing and debugging, you would likely want to move it to /usr/local/bin (as root, of course), to make the script available to yourself and all other users as a systemwide executable.

經過測試與除錯後,最後一步我們通常都會想將腳本搬到 /usr/local/bin 目錄下 (當然,以root身份來執行),讓系統上所有使用者都能使用這個腳本。

The script could then be invoked by simply typing scriptname [ENTER] from the command-line.

接著我們只要打腳本名稱[按下ENTER],就可直接執行了。

Notes

[1] Caution: invoking a Bash script by sh scriptname turns off Bash-specific extensions, and the script may therefore fail to execute.

注意:使用 sh scriptname 來執行腳本,可能會導致 Bash 相關的 extensions 無法使用,腳本也就因此執行失敗。

[2] A script needs read, as well as execute permission for it to run, since the shell needs to be able to read it.

賦予腳本「執行」權限時也須賦予「讀」的權限,因為shell在執行時需要「讀」它。

[3] Why not simply invoke the script with scriptname?

為何不乾脆用腳本名來執行腳本就好?

If the directory you are in ($PWD) is where scriptname is located, why doesn't this work?

假如現在所在的位置跟腳本同一目錄下,為何腳本無法成功執行?

This fails because, for security reasons, the current directory (./) is not by default included in a user's $PATH.

原因是考量到安全的因素,當前所在目錄(./)並不包含使用者的$PATH

It is therefore necessary to explicitly invoke the script in the current directory with a ./scriptname.

因此,此情況下若要執行腳本,就得使用./scriptname來執行。