Bash: How to Extract Directory from a File Path


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

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

Here is how to use this command in practice:

my_dir="$(dirname "${my_file}")"

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

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

Example: How to Extract Directory from File 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 directory of this file, which would be the following:

  • c:/users/bobbi

We can use the following syntax to do so:

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

my_dir="$(dirname "${my_file}")"

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

Bash extract directory from file path

Notice that when we use the echo statement to view the contents of the $my_dir variable we can see that it contains the directory for the file path that we specified.

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

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