Bash Bash Parameter Expansion Parameter expansion and filenames


Example

You can use Bash Parameter Expansion to emulate common filename-processing operations like basename and dirname.

We will use this as our example path:

FILENAME="/tmp/example/myfile.txt"

To emulate dirname and return the directory name of a file path:

echo "${FILENAME%/*}"
#Out: /tmp/example

To emulate basename $FILENAME and return the filename of a file path:

echo "${FILENAME##*/}"
#Out: myfile.txt

To emulate basename $FILENAME .txt and return the filename without the .txt. extension:

BASENAME="${FILENAME##*/}"
echo "${BASENAME%%.txt}"
#Out: myfile