dirname: That slash-mark filter you always wanted

I should probably mention dirname out of coreutils today, since it effectively reverses what we saw the other day with basename. This is easier to show than explain.

kmandla@6m47421: /usr/share/pixmaps$ dirname /usr/share/pixmaps

dirname strips away the directory and shows only the path up to the final folder. In the example it was the current directory — you get the same results from dirname $(pwd) — but you can feed it any path (or more than one), so it’s not correct to say “your current directory.”

If you feed dirname a path and file name, you get the path of to the file, which is where dirname becomes useful.

kmandla@6m47421: ~$ dirname /home/kmandla/downloads/list.html.txt 

Now you can effectively strip away the filename from a string, and leave only the path to it.

kmandla@6m47421: ~$ dirname $(find /usr/share/pixmaps/ -type f -iname "*png") | sort -u

So I know I have png files somewhere inside /usr/share/pixmaps, /usr/share/pixmaps/pidgin, and so on.

Now comes the strange part: If you give dirname a file in your current path, you get a lonesome dot.

kmandla@6m47421: ~$ dirname .bashrc 

This strikes me as odd behavior, since this is also dirname‘s response:

kmandla@6m47421: ~$ dirname /home/kmandla/.bashrc 

The man page comes to the rescue this time, and after reading that, I would hazard to guess that dirname is just traipsing along the string until it reaches the last slash, then dumping everything before that to STDOUT. No slashes means … a dot. 😕

And my suspicions are confirmed with this:

kmandla@6m47421: ~$ dirname this/is/a/test

So basically dirname is a filter for slash marks, and whether or not that represents an actual folder tree on your system is … moot. 🙄

dirname is useful in the same way as basename, but again, I can’t give you any tried-and-true uses that aren’t specific to my own real-life adventures. I leave it to you to come up with something earth-shattering and life-changing to use with dirname. It’s not an impossibility, even if it is just a slash-mark filter. … 😉

3 thoughts on “dirname: That slash-mark filter you always wanted

  1. John

    One thing I’ve found myself using dirname for, in scripts:
    HERE=`dirname $0`
    Or even
    cd `dirname $0`
    If you need to find other files that are in a known location relative to the script you’re writing, it’s useful.

    If you want to get the full path, rather than dot, you can always combine it with realpath:
    dirname `realpath .bashrc`

    It may say something weird about me that I was familiar with the equivalent functions from GNU’s Make before the CLI utilities. But if one of your other readers is in the same boat… could be useful to know most of those functions have direct equivalents on the command line. https://www.gnu.org/software/make/manual/html_node/File-Name-Functions.html

  2. Pingback: realpath: It’s the real thing | Inconsolation

Comments are closed.