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.
1file_path="/path/to/package.tar.gz"
2file_name=$(basename "$file_path")
3echo "$file_name"Output:
1package.tar.gzGet the file extension
Using shell parameter expansion, the prior example can include capturing the file extension:
1file_path="/path/to/package.tar.gz"
2file_name=$(basename "$file_path")
3file_ext="${file_name#*.}"
4echo "$file_ext"Output:
1tar.gzMatch 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)
1file_path="/path/to/package.tar.gz"
2file_name=$(basename "$file_path")
3
4case "$file_name" in
5 *.tar.gz) echo "matched tar.gz!" ;;
6esacOutput:
1matched tar.gz!