bash 花括号语法 ${var%.*} 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9558986/
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 does the curly-brace syntax ${var%.*} mean?
提问by Matt Norris
I was reviewing some of my old code and came across this syntax:
我正在我的一些旧代码并遇到以下语法:
extractDir="${downloadFileName%.*}-tmp"
The only information I found searching refers to a list of commands, but this is just one variable. What does this curly-brace syntax mean in bash?
我发现搜索的唯一信息是指命令列表,但这只是一个变量。这个花括号语法在 bash 中是什么意思?
回答by Jonathan Leffler
In this context, it is a parameter substitution.
在这种情况下,它是一个参数替换。
The ${variable%.*}notation means take the value of $variable, strip off the pattern .*from the tail of the value —?mnemonic: percenT has a 't' at the Tail — and give the result. (By contrast, ${variable#xyz}means remove xyzfrom the head of the variable's value — mnemonic: a Hash has an 'h' at the Head.)
的${variable%.*}符号取装置的值$variable,剥去图案.*从值的尾-助记符:百分之具有“T”在尾-和得到的结果。(相比之下,${variable#xyz}意味着xyz从变量值的头部移除——助记符:哈希在头部有一个“h”。)
Given:
鉴于:
downloadFileName=abc.tar.gz
evaluating extractDir="${downloadFileName%.*}-tmp"yields the equivalent of:
评估extractDir="${downloadFileName%.*}-tmp"产量相当于:
extractDir="abc.tar-tmp"
The alternative notation with the double %:
使用 double 的替代符号%:
extractDir="${downloadFileName%%.*}-tmp"
would yield the equivalent of:
将产生相当于:
extractDir="abc-tmp"
The %%means remove the longest possible tail; correspondingly, ##means remove the longest matching head.
该%%装置取出最长可能的尾; 相应地,##意味着删除最长的匹配头。
回答by Ignacio Vazquez-Abrams
It indicates that parameter expansionwill occur.
它表示将发生参数扩展。
回答by Matt T
It is used when expanding an environment variable adjacent to some text that is not the variable, so the shell does not include all of it in the variable name.
它用于扩展与不是变量的某些文本相邻的环境变量,因此 shell 不会将其全部包含在变量名称中。

