| dirname | |
|---|---|
| Developers | Variousopen-source andcommercial developers |
| Written in | C |
| Operating system | Unix,Unix-like,IBM i |
| Platform | Cross-platform |
| Type | Command |
| License | coreutils:GPLv3+ |
dirname is ashellcommand for extracting thedirectory path portion of apath; without the last name. The command is specified in theSingle UNIX Specification and is primarily used inshell scripts.
The version inGNU Core Utilities was written by David MacKenzie and Jim Meyering.[1] The command is available forWindows as part of theGnuWin32 project[2] andUnxUtils[3] and is inIBM i.[4]
TheSingle UNIX Specification is:dirname path. The required argument,path, is a file path string.
The command reports the directory path portion of a path ignoring any trailing slashes.
$dirname/path/to/filename.ext/path/to$dirname/path/to//path$dirnamefilename.ext.
Since the command accepts only one operand, its usage within theinner loop of a shell script can be detrimental to performance. Consider:
whilereadfile;dodirname"$file"done<some-input
The above causes a separate process invocation for each line of input. For this reason, shell substitution is typically used instead:
echo"${file%/*}";
Or, if relative pathnames need to be handled as well:
if[-n"${file##*/*}"];thenecho"."elseecho"${file%/*}";fi
Note that these handle trailing slashes differently thandirname.
dirname(1) – Linux UserManual – User Commands from Manned.orgdirname: return the directory portion of a pathname – Shell and Utilities Reference,The Single UNIX Specification, Version 5 fromThe Open Groupdirname(1) – Linux User CommandsManualdirname(1) – OpenBSD General CommandsManual