脚本如何在 bash 中知道自己的名字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2805165/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:05:32  来源:igfitidea点击:

How a script know his own name in bash?

bashpath

提问by Debugger

I launch script.sh and inside it i want to know what is his name

我启动 script.sh 并在里面我想知道他的名字是什么

Is there a standard procedure to know the scripts name ? the idea is to be able to extract the name from teh full path + name contained in $0

是否有知道脚本名称的标准程序?这个想法是能够从包含在的完整路径+名称中提取名称$0

Thanks

谢谢

回答by seamus

Yes, $0will always contain the name of the script. Use basename to extract the name.

是的,$0将始终包含脚本的名称。使用 basename 提取名称。

basename /some/really/long/dir/path/myscripts/coolscript.shwill print coolscript.sh

basename /some/really/long/dir/path/myscripts/coolscript.sh将打印 coolscript.sh

So in your script, you could do this:

所以在你的脚本中,你可以这样做:

my_scriptname="$(basename 
script="${0##*/}"
)"

回答by Paused until further notice.

##代码##

Edit:

编辑:

This does the same thing as basename $0. It strips off the last slash and everything before it from $0using Bash's brace expansion.

这与basename $0. 它从$0使用 Bash 的大括号扩展中去除了最后一个斜线和它之前的所有内容。

回答by Vincent Robert

basename $0will give you the script name

basename $0会给你脚本名称