bash 中带有变量、大括号和哈希字符的 ${0##...} 语法是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2059794/
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
What is the meaning of the ${0##...} syntax with variable, braces and hash character in bash?
提问by user215997
I just saw some code in bash that I didn't quite understand. Being the newbie bash scripter, I'm not sure what's going on.
我刚刚在 bash 中看到了一些我不太明白的代码。作为新手 bash 脚本编写者,我不确定发生了什么。
echo ${0##/*}
echo ${string#substring}
I don't really see a difference in output in these two commands (prints the script name). Is that #
just a comment? And what's with the /*
. If it is a comment, how come it doesn't interfere with the closing }
brace?
我真的没有看到这两个命令的输出差异(打印脚本名称)。这#
只是评论吗?和/*
. 如果是注释,它怎么不干扰}
右大括号?
Can anyone give me some insight into this syntax?
任何人都可以让我深入了解这种语法吗?
回答by Mark Byers
See the section on Substring removalin the Advanced Bash-Scripting Guide?:
请参阅高级 Bash 脚本指南中的子字符串删除部分?:
${string##substring}
Deletes shortest match of
substring
from front of$string
.${string#substring}
Deletes longest match of
substring
from front of$string
.
${string##substring}
删除
substring
从前面的最短匹配项$string
。${PARAMETER##WORD} Results in removal of the longest matching pattern from the beginning rather than the shortest. for example [ian@pinguino ~]$ x="a1 b1 c2 d2" [ian@pinguino ~]$ echo ${x#*1} b1 c2 d2 [ian@pinguino ~]$ echo ${x##*1} c2 d2 [ian@pinguino ~]$ echo ${x%1*} a1 b [ian@pinguino ~]$ echo ${x%%1*} a [ian@pinguino ~]$ echo ${x/1/3} a3 b1 c2 d2 [ian@pinguino ~]$ echo ${x//1/3} a3 b3 c2 d2 [ian@pinguino ~]$ echo ${x//?1/z3} z3 z3 c2 d2
substring
从 前面删除最长的匹配项$string
。
The substring may include a wildcard *
, matching everything. The expression ${0##/*}
prints the value of $0
unless it starts with a forward slash, in which case it prints nothing.
子字符串可能包含通配符*
,匹配所有内容。该表达式${0##/*}
打印 的值,$0
除非它以正斜杠开头,在这种情况下它不打印任何内容。
? The guide, as of 3/7/2019, mistakenly claims that the match is of $substring
, as if substring
was the name of a variable. It's not: substring
is just a pattern.
? 截至 2019 年 3 月 7 日,该指南错误地声称匹配项为$substring
,就好像substring
是变量的名称一样。它不是:substring
只是一种模式。
回答by Paul Creasey
回答by Ignacio Vazquez-Abrams
See the Parameter Expansion
section of the bash(1)
man page.
请参阅手册页的Parameter Expansion
部分bash(1)
。