In a bash script, you need to get a filename and extension to save it into a variable.

This tutorial explains to find the filename and extension for a given file.

This article covers

  • Extract the file name for a given full path
  • getting the full file name
  • Extension name

How to extract file name with extension

the basename uses to remove the directory and return the filename for the given path. the path is variable or string. For example, the path is /home/john/run.sh and returned file name is run.sh In this, the full path is given and returns the filename by removing the path.

And the filename is saved to a variable and printed to the console.

file_path="/home/john/run.sh"
filename=$(basename "$file_path")
echo $filename

output:

run.sh

Extract filename

In this, For a given path, return the file name only without an extension ${filename%.*} returns the file name.

filepath="/home/john/run.sh"
filename=$(basename "$filepath")
echo $filename
echo "File Name: ${filename%.*}"

output:

File Name: run

Extract extension for a file path

In this, Get the only extension for a given file path. ${filename##*.} returns file extension

filepath="/home/john/run.sh"
filename=$(basename "$filepath")
echo $filename
echo "File Extension: ${filename##*.}"

Output

File Extension:sh

Here is a complete example of getting a filename with or without a file extension On running the below script, It prints

  • File with extension
  • Only Prints file name without extension
  • Extension only

Example:

filepath="/home/username/run.sh"
filename=$(basename "$filepath")
echo "File :$filename"
echo "File Name: ${filename%.*}"
echo "File Extension: ${filename##*.}"

Output

File:run.sh
File Name:run
File Extension:sh