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

每个 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.

posted @   紫云飞  阅读(1854)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示