Get file name or extension in Bash

Retrieving the file name and extension in Bash can be completed using basename and shell parameter expansion.

Get the file name

Using the native unix basename command, the file name can be extracted from the path.

1
2
3
file_path="/path/to/package.tar.gz"
file_name=$(basename "$file_path")
echo "$file_name"

Output:

1
package.tar.gz

Get the file extension

Using shell parameter expansion, the prior example can include capturing the file extension:

1
2
3
4
file_path="/path/to/package.tar.gz"
file_name=$(basename "$file_path")
file_ext="${file_name#*.}"
echo "$file_ext"

Output:

1
tar.gz

Match on file extension using a case statement

If there is conditional logic required for specific file extensions, a case statement may be used. In addition, this is standard sh (not exclusive to bash)

1
2
3
4
5
6
file_path="/path/to/package.tar.gz"
file_name=$(basename "$file_path")

case "$file_name" in
    *.tar.gz) echo "matched tar.gz!" ;;
esac

Output:

1
matched tar.gz!