Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 857
Matt Norris Avatar asked Mar 04 '12 21:03

Matt Norris


People also ask

What does curly brackets mean in shell script?

The curly braces tell the shell interpreter where the end of the variable name is.

What does curly brackets mean in Linux?

Bash brace expansion is used to generate stings at the command line or in a shell script. The syntax for brace expansion consists of either a sequence specification or a comma separated list of items inside curly braces "{}". A sequence consists of a starting and ending item separated by two periods "..".

What are {} used for in Bash?

Parameter expansion. Here the braces {} are not being used as apart of a sequence builder, but as a way of generating parameter expansion. Parameter expansion involves what it says on the box: it takes the variable or expression within the braces and expands it to whatever it represents.

What is ${} in Bash?

${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol. When a parameter is referenced by a number, it is called a positional parameter.


2 Answers

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.

like image 85
Jonathan Leffler Avatar answered Sep 23 '22 01:09

Jonathan Leffler


It indicates that parameter expansion will occur.

like image 31
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 01:09

Ignacio Vazquez-Abrams