Bash 中的 $0 在何時不是 argv[0]

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

不少人說 Bash 中的 $0 的值就是 bash 這個 C 程序在它的 main 函數中獲取到的 argv[0](zeroth argument)的值,咱們能夠經過 exec 命令的 -a 參數的功能演示一下:shell

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

foobash

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

...spa

$  ( exec -a "" bash -c 'echo $0' )操作系統

 

但並不都是這樣,在兩種狀況下,$0 的值不是 argv[0]:命令行

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

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

foo barhtm

這個時候 bash 程序的 argv[0] 是 「bash」,但 $0 倒是 「foo」。也就是說若是 -c 選項的參數後面還有參數,那麼那些參數會依次成爲 $0(覆蓋了舊的值 argv[0])、$一、$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.

相關文章
相關標籤/搜索