Bash Bash Parameter Expansion Parameter expansion and filenames

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Bash Question?