Linux dirname Command Explained for Beginners (4 Examples)
Are you a new Linux user? Does your work involve shell scripting? If your answer to both these questions is yes, the tool we'll be discussing here will likely interest you. The name of the tool is dirname, and it's mostly used in situations where-in you need to strip the last component from an absolute file-name.
In this tutorial, we will discuss the basics of dirname as well as how you can use it. But before we do that, it's worth sharing that all examples/instructions mentioned here have been tested on Ubuntu 22.04 LTS.
Linux dirname command
Following is the generic syntax of the dirname command:
dirname [OPTION] NAME...
Here's how the tool's man page describes it:
Output each NAME with its last non-slash component and trailing slashes removed; if NAME contains
no /'s, output '.' (meaning the current directory).
The following Q&A-type examples will give you a better idea of how the tool can be used. To change to a new directory, use the cd command.
Q1. How dirname command works?
The basic usage of the tool is very simple - just write the command name, followed by the absolute name of a file. In the output, you'll get the complete directory tree, except for the name of the file.
Here's an example:
Q2. Can it handle multiple inputs?
Yes, of course. All you need to do is to pass the absolute filenames one after the other. The following example should make this amply clear:
Q3. What if file's name is it's absolute name as well?
If the input is simply a filename (not the absolute one, complete with directory tree), then a dot (.) is produced in the output.
If you take a look at the man page description of the command again (mentioned in the beginning), this behavior is clearly mentioned there.
Q4. How to replace a newline with NUL in output lines?
By default, the lines in output are newline separated, as clear from the Q&A 2 above. However, if you want, you can have the output lines separated by NUL characters instead. For this, use the -z command line option.
Here's a screenshot of this command line option in action:
Observe that the output lines were no longer separated by a newline.
The dirname command might not be as feature-rich as some of the other Linux commands, but it would not be wrong to say that it's a nifty tool that may save your day while working with shell scripts. Whatever we've discussed here is pretty much all that the tool offers. In case you have any doubts or queries, leave a comment below.