Lee Xu
Lee Xu

Reputation: 35

What does ${2%.*} mean?

I am reading a bash script that takes two arguments in input but I can't figure out what does

${2%.*}

does exactly, can someone explain me what does the curly braces, 2, %, "." and * refers two?

Thanks

Upvotes: 2

Views: 462

Answers (1)

chepner
chepner

Reputation: 531798

$2 is the second argument passed to the program. That is, if your script was run with

myscript foo.txt bar.jpg

$2 would have the value bar.jpg.

The % operator removes a suffix from the value that matches the following pattern. .* matches a period (.) followed by zero or more characters. Put together, your expression removes a single extension from the value. Using the above example,

$ echo ${2%.*}
bar

P.S. Perhaps worth noting that % will remove the shortest match for the following pattern: So if $2 was for example bar.jpg.xz, then ${2%.*} would be bar.jpg. (Conversely, the %% operator will remove the longest match for the pattern, so ${2%%.*} would be bar in both examples.)

Upvotes: 6

Related Questions