文章出處

每個 C 程序都有一個 main 函數,每個 main 函數都有一個 argv 參數,這個參數是一個字符串數組,這個數組的值是由該 C 程序的父進程在通過 exec* 函數啟動它時指定的。

很多人說 Bash 中的 $0 的值就是 bash 這個 C 程序在它的 main 函數中獲取到的 argv[0](zeroth argument)的值,我們可以通過 exec 命令的 -a 參數的功能演示一下:

$  ( exec -a foo bash -c 'echo $0' )

foo

$ ( exec -a ... bash -c 'echo $0' )

...

$  ( exec -a "" bash -c 'echo $0' )

 

但并不都是這樣,在兩種情況下,$0 的值不是 argv[0]:

bash -c '...' foo bar ...

$  bash -c 'echo $0 $1' foo bar 

foo bar

這個時候 bash 程序的 argv[0] 是 “bash”,但 $0 卻是 “foo”。也就是說如果 -c 選項的參數后面還有參數,那么那些參數會依次成為 $0(覆蓋了舊的值 argv[0])、$1、$2...。

bash /a/b/c.sh

$  cat foo.sh

echo $0

$ bash foo.sh

foo.sh

$ bash ./foo.sh

./foo.sh

$ ./foo.sh

./foo.sh

這個時候 bash 程序的 argv[0] 還是 “bash”,但 $0 卻是 “foo.sh”。也就是說,當執行一個腳本時,$0 的值就是那個腳本的相對或絕對路徑(你指定的任意合法路徑)。你在命令行中輸入 ./foo.sh 也一樣,因為操作系統會為你執行 /bin/sh ./foo.sh。 

關于 $0 的值的這三種情況,Bash 文檔其實都有講,我分別用三種顏色標注相關話語:

($0) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see Shell Scripts), $0 is set to the name of that file. If Bash is started with the -c option (see Invoking Bash), then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()