如何获取在 bash 中执行的脚本名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14835193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the script name being executed in bash?
提问by David Mokon Bond
So I am trying to make a portable bashrc/bash_profile file. I have a single script that I am symbolically linking to .bashrc, .bash_profile, etc. I am then looking at $0and switching what I do based on which script was called. The problem is what the shell calls the bashrc script of course it executes bash really which means $0for me is -bash. $1further more is not set to the script name.
所以我正在尝试制作一个可移植的 bashrc/bash_profile 文件。我有一个脚本,我象征性地链接到 .bashrc、.bash_profile 等。然后$0我会根据调用的脚本查看并切换我的操作。问题是 shell 调用了 bashrc 脚本,当然它确实执行 bash,这$0对我来说意味着-bash. $1更进一步没有设置为脚本名称。
So my question is, in bash how can I get the name of the script being executed. Not the binary executing it, e.g. bash?
所以我的问题是,在 bash 中如何获取正在执行的脚本的名称。不是执行它的二进制文件,例如 bash?
I assume its giving me -bashwith $1not being set because it is really not a new process. Any ideas?
我认为它给了我-bash与$1未设置,因为这实在不是一个新的进程。有任何想法吗?
采纳答案by Steven Penny
The variable BASH_ARGVshould work, it appears the script is being sourced
该变量BASH_ARGV应该可以工作,它似乎正在获取脚本
$BASH_ARGV
回答by Hui Zheng
Try:
尝试:
readlink -f ${BASH_SOURCE[0]}
readlink -f ${BASH_SOURCE[0]}
or just:
要不就:
${BASH_SOURCE[0]}.
${BASH_SOURCE[0]}.
Remarks:
备注:
$0only works when user executes "./script.sh"
$0仅在用户执行“./script.sh”时有效
$BASH_ARGVonly works when user executes ". script.sh" or "source script.sh"
$BASH_ARGV仅在用户执行“.script.sh”或“source script.sh”时有效
${BASH_SOURCE[0]}works on both cases.
${BASH_SOURCE[0]}适用于两种情况。
readlink -fis useful when symbolic link is used.
readlink -f在使用符号链接时很有用。

