源 Bash 脚本中的 $0 未返回脚本名称
当我在运行 Bash 脚本中引用 $0 时“http://en.wikipedia.org/wiki/Mac_OS_X_Snow_Leopard” rel="nofollow noreferrer">Mac OS X v10.6.7 (Snow Leopard),我得到 -bash,而不是脚本的名称。
我运行了 此堆栈中描述的脚本溢出问题:
#!/bin/bash
echo
echo '# arguments called with ($@) --> '"$@"
echo '# $1 --------------------------> '"$1"
echo '# $2 --------------------------> '"$2"
echo '# path to me ($0) -------------> '"$0"
echo '# parent path (${0%/*}) -------> '"${0%/*}"
echo '# my name (${0##*/}) ----------> '"${0##*/}"
echo
产生以下内容:
> . show_parms.sh foo
# arguments called with ($@) --> foo
# $1 --------------------------> foo
# $2 -------------------------->
# path to me ($0) -------------> -bash
# parent path (${0%/*}) -------> -bash
# my name (${0##*/}) ----------> -bash
有什么想法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是有道理的,因为您是获取脚本
而不是执行它
,如 同一问题的答案,您可以使用
$BASH_SOURCE
来了解正在执行命令的文件的名称来源。That makes sense since you’re sourcing the script
instead of executing it
As explained in this answer to the same question, you can use
$BASH_SOURCE
to know the name of the file from which commands are being sourced.$0 返回进程的名称。通过使用 .运算符,您只需将脚本读入现有的 bash 进程并评估它包含的命令;进程的名称仍然是“-bash”,所以这就是您所看到的。您必须将脚本作为其自己的进程实际执行:
然后您就会得到您所期望的结果。这不是 OS X 特有的;这就是 bash(或 sh)的工作原理。
$0 returns the name of the process. By using the . operator, you're just reading the script into your existing bash process and evaluating the commands it contains; the name of the process remains "-bash", so that's what you see. You have to actually execute the script as its own process:
And then you'll get what you expect. This isn't OS X specific; this is just how bash (or sh) works.
这是因为您正在使用 .操作员。如果你只是输入,
你就会得到你想要的结果。
It is because you are using the . operator. If you just typed
you would get the result you want.