Linux command: dirname
The Linux command, dirname
strips the last component from a given file name.
The dirname
is a built-in command and it will output, the complete directory tree; except for the name of the file.
This article shows the usage of dirname command with example.
It simply strips the last part of a file name(after the last forward-slash /
) and gives the remaining part containing the name of the directory where that file is saved.
The dirname
command
It can be used to identify paths in the shell scripts.
Syntax
dirname [OPTION] NAME...
Options
-z
,--zero
End each output line with NUL, not newline
--help
Exits after displaying the help
--version
Exits after displaying version information
Example 1
dirname /home/meshworld/Documents/IntroToUbuntu.docx
# Output -> /home/meshworld/Documents
dirname /home/meshworld/Music/
# Output -> /home/meshworld/Music
dirname DummiesForLinux.pdf
# Output -> .
Example 2
We can also extract the path info and save the result into another variable.
filePath="/home/meshworld/Pictures/TajMahal.jpg"
directoryPath=$(dirname $filePath)
echo "File path: $filePath"
echo "Directory path: $directoryPath"
Output:
File path: /home/meshworld/Pictures/TajMahal.jpg
Directory path: /home/meshworld/Pictures
Conclusion
The dirname
command comes handy when we need to retrieve path, where the file exists.
Hope you like this!
Keep helping and happy 😄 coding