日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Bash 中的 $0 在什么时候不是 argv[0]

發(fā)布時間:2023/12/31 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Bash 中的 $0 在什么时候不是 argv[0] 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

每個 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。