Dirname


dirname is a standard computer program on Unix and Unix-like operating systems. When dirname is given a pathname, it will delete any suffix beginning with the last slash character and return the result. dirname is described in the Single UNIX Specification and is primarily used in shell scripts.

History

The version of dirname bundled in GNU coreutils was written by David MacKenzie and Jim Meyering.

Usage

The Single UNIX Specification for dirname is:
dirname string

Examples

dirname will retrieve the directory-path name from a pathname ignoring any trailing slashes

$ dirname /home/martin/docs/base.wiki
/home/martin/docs
$ dirname /home/martin/docs/.
/home/martin/docs
$ dirname /home/martin/docs/
/home/martin
$ dirname base.wiki
$ dirname /

Performance

Since dirname accepts only one operand, its usage within the inner loop of shell scripts can be detrimental to performance. Consider

while read file; do
dirname "$file"
done < some-input

The above excerpt would cause a separate process invocation for each line of input. For this reason, shell substitution is typically used instead

echo "$";

or if relative pathnames need to be handled as well

if ; then
echo "."
else
echo "$";
fi

Note that these handle trailing slashes differently than dirname.

Misconceptions

We might think that paths that end in a trailing slash are a directory. But actually, the trailing slash represents all files within the directory.
/home/martin/docs/.