Bash: How to Extract Filename from a Path


Often you may want to extract a filename from a path in Bash.

The easiest way to do so is by using the basename command, which is designed to perform this exact task.

Here is how to use this command in practice:

my_file="$(basename "${my_path}")"

This particular example extracts the filename from the path specified by the $my_path variable and saves the results in a new variable named $my_file.

The following example shows how to use this syntax in practice.

Example: How to Extract Filename from Path in Bash

Suppose that we have a file named teams.txt with the following file path:

  • c:/users/bobbi/teams.txt

Suppose that we would like to extract only the filename, which would be the following:

  • teams.txt

We can use the following syntax to do so:

my_path='/c/users/bobbi/teams.txt'

my_file="$(basename "${my_path}")"
echo $my_file

The following screenshot shows how to use this syntax in practice:

Bash extract filename from path

Notice that when we use the echo statement to view the contents of the $my_file variable we can see that it contains only the filename for the path that we specified.

Bonus: To instead extract only the directory from the path, you can replace basename with dirname.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: Count Number of Lines in Each File in Directory
Bash: How to Count Number of Folders in a Directory
Bash: How to Add Prefix to All Files in Directory
Bash: How to Add Prefix to All Files in Directory

Leave a Reply