When you need to get the directory name of a file but you only have the full path to the file, what do you do? You could use some fancy parameter expansion, sure, but you might run into some weird edge cases. Personally, I’d suggest just using
If you’re familiar with Python and the
os library, the behavior is the same as
os.path.dirname, but even if you’re not, it’s still pretty straightforward. Let’s look at the
man page for the command. It states that given a path, it will output it “with its last non-slash component and trailing slashes removed.” If the path contains no path separators, it will output
., which is the current directory.
So in a nutshell, that means it will normalize
.. Because it removes trailing slashes and because it’s not dependent on any file extensions, you can use it repeatedly to move further and further up the tree:
So when is this useful? Well, if you’ve got something in your path and you want to find out what else is in that directory, you could do something like this:
Maybe you want to navigate to that directory or open it in some other command? Yeah, you can do that too.
If you’re still not convinced that you should use
dirname, check out this amazing stack overflow reply about some of the differences between parameter expansion and