8

Why does this command work in successfully retrieving file extension name?

file_ext=${filename##*.}
0

2 Answers 2

11

This is described in the POSIX Shell Command Language:

${parameter##word}

Remove Largest Prefix Pattern. The word shall be expanded to produce a pattern. The parameter expansion shall then result in parameter, with the largest portion of the prefix matched by the pattern deleted.

In that specific case, *. is expanded to the largest substring that ends with a . (* matching anything), and that largest substring is removed. So only the file extension is left.

Note that nothing is removed if the filename doesn't contain a ., so be careful when using this in scripts, the behavior might not be what you expect.

9

Have a look at man bash (or whatever shell you are using):

   ${parameter##word}
          Remove matching prefix pattern.  The word is expanded to produce
          a pattern just as in pathname expansion.  If the pattern matches
          the  beginning of the value of parameter, then the result of the
          expansion is the expanded value of parameter with  the  shortest
          matching  pattern  (the ``#'' case) or the longest matching pat‐
          tern (the ``##'' case) deleted.  If parameter is  @  or  *,  the
          pattern  removal operation is applied to each positional parame‐
          ter in turn, and the expansion is the resultant list.  If param‐
          eter  is  an array variable subscripted with @ or *, the pattern
          removal operation is applied to each  member  of  the  array  in
          turn, and the expansion is the resultant list.

Hence in your case it removes everything up to the last "." and returns the remaining string, which happens to be the extension of the file.

Not the answer you're looking for? Browse other questions tagged .