get filename from path in shell script

How to Get Filename from Path in Shell Script

Sometimes you may need to retrieve file name from a given path in shell script. In this article, we will look at how to get filename from path in shell script.


How to Get Filename from Path in Shell Script

Here are the steps to get filename from path in shell script.


1. Create Shell Script

Open terminal and run the following command to create empty shell script

$ sudo vi get_filename.sh


2. Add Shell Script

You can use basename command to get file name from full path. It removes directory and extension from file path. Here is an example.

#!/bin/bash
input="/home/data.txt"
# extract data.txt
file_name="${input##*/}"
# get .txt 
file_extension="${file_name##*.}"
# get data 
file="${file_name%.*}"
# print the different variables
echo "Full input file : $input"
echo "Filename only : $file_name"
echo "File extension only: $file_extension"
echo "First part of filename only: $file"

Save and exit the file. Let us look at the above code line by line. First we define shell script’s execution environment. We store the full file path in $input variable. Then we use various parameter expansion syntaxes to extract filename with extension, file extension and only first part of filename. You can read more about parameter expansion in shell scripts here.


3. Make Shell Script Executable

Run the following command to make it executable.

$ sudo chmod +x get_filename.sh


4. Run Shell Script

Run the following command to test your shell script

$ ./get_filename.sh
Full input file : /home/data.txt
Filename only : data.txt
File extension only: txt
First part of filename only: data

Also read:

Shell Script to Trim Whitespace
How to Disable HTTP TRACE Method in Apache
How to Switch User in Ubuntu Linux
How to Bring Background Process to Foreground in Linux
LS File Size in kb, Mb

Leave a Reply

Your email address will not be published. Required fields are marked *