Commands

Using Linux Dirname Command in Bash Scripts

The dirname command in Linux extracts the directory path from a file path. Learn some practical examples of using dirname command in bash scripts.

Abhishek Prakash
Abhishek Prakash

The dirname command in Linux prints a file path with its final component removed. This basically gives you the directory path from the file path.

dirname command example

This is particularly helpful in bash scripts where you want to extract the directory path from the long file path.

The dirname command is complementary to the basename command. The basename command extracts the file name from path while dirname extracts the directory path.

Let me show it to you with some examples.

Dirname command examples

The dirname command a straightforward syntax.

dirname OPTION PATH

Using dirname command with the absolute path of a file will give the directory path:

dirname /home/user/data/filename.txt
/home/user/data

Like the basename command, the dirname command is also stupid actually. It doesn’t really recognize file path. It just looks for the slashes (/) and prints the whatever is before the last slash. Basically, you can give it any string with / in it and it will work on it.

For example, I am using a random string here with no filename in it. You can see that it still works the same and outputs a string removing the last / and the text after it.

dirname command in Linux

If the path has no slash (/) in it, it will output a dot (.) implying the current directory.

dirname command example

You can use dirname with multiple paths as well. It will return the output for each path in a new line:

dirname command

You may use the -z option to get the result in the same line with outputs separated by NULL character.

Using dirname in bash script

I showed some examples of the dirname command. Let’s talk about using dirname in bash scripts.

Suppose you have a file path variable and you want to get the path to the directory that contains the file. This could be a simple script:

pathname="/home/dir/data/filename"

result=$(dirname "$pathname")

echo $result

As I mentioned earlier, the dirname command is complemented with the basename command. Unlike dirname, the basename command prints only the last component of the path.

I hope you liked this tutorial. As always, feel free to ask questions or provide suggestions in the comment section.

Liked the article? Please share it and help us grow :)



Join the conversation.