個人博客地址:Shell $0 | 一張假鈔的真實世界
我們已經知道在Shell中$0
表示Shell腳本的文件名,但在有腳本調用的情形中,子腳本中的$0
會是什么值呢?我們通過下面的實例來看。
已測試系統列表:
- Mac OS X EI Capitan 10.11.6
- Ubuntu 16.04 LTS (GNU/Linux 4.4.0-28-generic x86_64)
父腳本a.sh
,位置test1/a.sh
,內容如下:
!/usr/bin/env bashecho "$0"
. ../test2/b.sh
子腳本b.sh
,位置test2/b.sh
,內容如下:
#!/usr/bin/env bashecho "the sub script is: $0"
此時執行父腳本輸出結果是:
$ sh a.sh
the main script is a.sh
the sub script is: a.sh
如果父腳本內容如下:
#!/usr/bin/env bashecho "the main script is $0"
../test2/b.sh
則輸出結果為:
$ sh a.sh
the main script is a.sh
the sub script is: ../test2/b.sh
可見,在父腳本中調用子腳本的不同,在子腳本中$0
的值也不同。至于為什么會這樣本人需要繼續學習以找到答案。
測試過程中注意給腳本賦可執行權限。