Bash – Get file extension

To get extension of a file in Bash scripting, first separate the file name from the given file path, and remove the last period character and anything before that.

The syntax of the expression to get the file name from given file path is given below.

</>
Copy
file_name="${file_path##*/}"

The syntax of the expression to get the file extension from given file name is given below.

</>
Copy
extension="${file_name##*.}"

Example

In the following script, we take the path of file in file_path. We get the extension of the file and print it to the output using echo.

example.sh

</>
Copy
#!/bin/bash

file_path="/Users/tutorialkart/Desktop/sample.txt"
file_name="${file_path##*/}"
extension="${file_name##*.}"
echo "$extension"

Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)

Output

sh-3.2# bash example.sh 
txt

Conclusion

In this Bash Tutorial, we learned how to get the extension from a given file path.