How To Use The Dirname Command on Linux Bash scripts

The dirname command on Linux prints the path to the file with the last component removed. This basically gives you the directory path from the file path. The dirname command complements the basename command. The basename command retrieves the file name from the path, while dirname retrieves the directory path.

Dirname Command Examples

Dirname command has very simple syntax

dirname OPTION PATH

Using the command will give the directory path:

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

Like the basename command, the dirname command is actually primitive. It really does not recognize the file path. It just searches for slashes (/) and prints everything that is before the last slash. In fact, you can ask him any line with / in it, and it will work with it. For example: a random string without a file name is very often used. It is possible to see that it still works the same way and displays a line, deleting the last / and the text after it

destroyer@hostry: ~$ dirname dir1/dir2/dir3/dir4
dir1/dir2/dir3
destroyer@hostry: ~$

If there is no forward slash (/) in the path, a period (.) Will be displayed, indicating the current directory

destroyer@hostry: ~$ dirname hostry.txt
.
destroyer@hostry: ~$

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

destroyer@histry: ~$ dirname dir1/file dir2/file
dir1
dir2
destroyer@hostry: ~$

You can use the -z option to get the result on the same line as the output, separated by a NULL character.

Using Dirname in a Bash Script

Some examples of using the dirname command have been shown. Now, for example, the following will be taken: you have a file path variable and you need to get the path to the directory where this file is located. It could be a very simple script

pathname="/home/dir/data/filename"
result=$(dirname "$pathname")
echo $result

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

Was this article helpful?

Related Articles

Leave A Comment?