Like it!

Join me on Facebook!

Like it!

How to get basename from file path in Bash

A one-line solution thanks to the Parameter Expansion.

Say you have a variable FULL_PATH that contains the full path of a specific file (for example /path/to/my/file.txt) and you want to keep only the basename (i.e. file.txt). The solution: use the so-called "Parameter Expansion", like that:

FULL_PATH=/path/to/my/file.txt
echo ${FULL_PATH##*/} # prints 'file.txt'

The Parameter Expansion magic explained

Anytime you use a dollar sign followed by a variable name you are doing the Parameter Expansion. For example echo $FULL_PATH or X=$FULL_PATH. Sometimes the variable is surrounded by braces, e.g. ${FULL_PATH}.bak which, when printed or used is expanded (that's where the expression come from) to /path/to/my/file.txt.bak. In other words, Parameter Expansion refers to any operation that causes a parameter to be replaced by some other content.

The curly-brace tool introduces several syntaxes. We have just used one of those for our basename trimming, which is ${parameter##word}. Here the word part is is a pattern that is used to remove a part of the string parameter, by matching it from the beginning. The operator "##" will try to remove the longest text matching. We used the pattern */, which matches (i.e. removes) anything until the last / encountered.

Sources

Bash manual - Shell Parameter Expansion (link)
Linux Journal - Bash Parameter Expansion (link)
Bash Hackers Wiki - Parameter expansion (link)

comments