How to Get Filename from the Full Path in Linux

The full path of a file in Linux refers to the complete address including directories and subdirectories using which the file can be located. Every operating system has different variants of the full path of a file.

In Linux, it looks something like the following:

/home/user/Documents/test.txt

This is the full file path of file test.txt.

When manually dealing with a file path, it is easy to get the filename, but if you are using a script for some kind of automation, you might need to extract the filename in certain scenarios.

Let’s see how we can extract filename out of the full path in Linux.

Using Basename Command

The whole purpose of the basename command is to retrieve filename out of a file path. Although it is not too difficult to get the filename from a full path, basename automatically does it for you and you don’t have to go through the trouble of parsing the file path, etc.

Syntax is:

$ basename full_file_path
$ basename /var/log/syslog   [example command]
Print File Name
Print File Name

Use the -a an argument to pass multiple paths.

$ basename -a /var/log/syslog /var/log/dpkg.log
Print File Names
Print File Names

Using Bash Parameter Substitution

Bash Parameter Substitutions are a way to modify a variable on the fly. Hence to use this method, we need to store the file path in a variable.

$ fullpath="/var/log/syslog"

Now we will apply parameter substitution and store the value in another variable.

$ filename=${fullpath##*/}
$ echo $filename
Store Value in Variable
Store Value in Variable

Basically what this does is that: it shreds the part before the last ‘/’ in ‘full path’ and just keeps the rest of the string, which is nothing but the filename.

Conclusion

In this article, we learned about two ways to get a filename from a full file path in Linux. If you want to learn more about the command basename and parameter substitutions in Bash, make sure you go through their respective man pages with:

$ man basename
$ man bash

Thanks for reading and let us know your thoughts and questions below!

Got something to say? Join the discussion.