Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

bash - What does the curly-brace syntax ${var%.*} mean?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 xyz from the head of the variable's value — mnemonic: a Hash has an 'h' at the Head.)

Given:

downloadFileName=abc.tar.gz

evaluating extractDir="${downloadFileName%.*}-tmp" yields the equivalent of:

extractDir="abc.tar-tmp"

The alternative notation with the 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...