Dirname Command in Linux with Examples
dirname is a command in Linux that is used to remove the trailing forward slashes “/” from the NAME and print the remaining portion. If the argument NAME does not contain the forward slash “/” then it simply prints dot “.”. In other words, we can say that the ‘dirname’ command is a useful tool for extracting the directory portion from a given path or filename.
Syntax
dirname [OPTION] NAME
Where,
- NAME is the file or directory path from which the directory portion will be extracted.
- OPTION allows for additional functionality such as version checking or line-ending control.
Basic Example: Extracting the Directory Name from a Full Path
We know that it is used to extract the directory name from a given file path.
dirname /Desktop/root/bash.sh

dirname /Desktop/root/bash.sh
Here we can see that our whole path is “/Desktop/root/bash.sh”, where we have an output “/Desktop/root” which is our directory name, and “bash.sh” was our file name.
dirname bash.sh

dirname bash.sh
Here we can see that no path is mentioned on file name “bash.sh” is mentioned. Our output shows “.” which means that we are in the current directory.
Common Options available for dirname Command
1. `-z or -zero` Option in `dirname` command in Linux
This option provides a way to end the line by a null command rather than a new line. Using this the next command will execute on the same line rather than on the next line.
Syntax:
dirname -zero NAME or dirname --z NAME
Example:
dirname -z /Desktop/root/bash.sh

dirname -z /Desktop/root/bash.sh
As we can see we end the line with a null command rather than a new line.
2. `–help` Option in `dirname` command in Linux
It displays helpful information.
dirname --help

dirname –help
3. `–version` Option in `dirname` command in Linux
It displays version information.
dirname --version

dirname –version
Conclusion
In this article we discussed the `dirname` command in Linux. Which provides a simple and effective way to extract the directory portion from a given file path or name. By going through this article one can understand that `dirname` command helps in manipulating and working with the file path efficiently.
Dirname Command in Linux – FAQs
What does the dirname command do in Linux?
The dirname command extracts and returns the directory portion of a file path, removing the file name and any trailing slashes.
How does dirname handle paths without slashes?
If the provided file name doesn’t include a path (i.e., no forward slashes), dirname returns a dot (.), indicating the current directory.
What is the -z option in dirname used for?
The -z or –zero option ends the output with a null character (\0) instead of a newline, which is useful in scripting environments that require null-terminated strings.
How can I check the version of dirname?
Use the –version option to check the version of the dirname command:
dirname --version