Bash 中的 $0 在什么时候不是 argv[0]
每個 C 程序都有一個 main 函數(shù),每個 main 函數(shù)都有一個 argv 參數(shù),這個參數(shù)是一個字符串?dāng)?shù)組,這個數(shù)組的值是由該 C 程序的父進(jìn)程在通過 exec* 函數(shù)啟動它時指定的。
很多人說 Bash 中的 $0 的值就是 bash 這個 C 程序在它的 main 函數(shù)中獲取到的 argv[0](zeroth argument)的值,我們可以通過 exec 命令的 -a 參數(shù)的功能演示一下:
| $??( 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 選項(xiàng)的參數(shù)后面還有參數(shù),那么那些參數(shù)會依次成為 $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”。也就是說,當(dāng)執(zhí)行一個腳本時,$0 的值就是那個腳本的相對或絕對路徑(你指定的任意合法路徑)。你在命令行中輸入 ./foo.sh 也一樣,因?yàn)椴僮飨到y(tǒng)會為你執(zhí)行 /bin/sh ./foo.sh。?
關(guān)于 $0 的值的這三種情況,Bash 文檔其實(shí)都有講,我分別用三種顏色標(biāo)注相關(guān)話語:
($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.
總結(jié)
以上是生活随笔為你收集整理的Bash 中的 $0 在什么时候不是 argv[0]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网易邮箱大师如何退出账号(网易游戏官网)
- 下一篇: 计算机科学家Erik Meijer眼中的