dirname
{{Short description|Shell command in Unix systems}}
{{Lowercase title}}
{{Infobox software
| name = dirname
| logo =
| screenshot = Dirname example.png
| screenshot size =
| caption = Example of dirname
command
| author =
| developer = Various open-source and commercial developers
| released =
| latest release version =
| latest release date =
| operating system = Unix, Unix-like, IBM i
| platform = Cross-platform
| genre = Command
| website =
}}
dirname
is a shell command for extracting the directory path portion of a path; without the last name. The command is specified in the Single UNIX Specification and is primarily used in shell scripts.
The version in GNU Core Utilities was written by David MacKenzie and Jim Meyering.{{Cite web|url=https://linux.die.net/man/1/dirname|title = Dirname(1) - Linux man page}} The command is available for Windows via UnxUtils,{{Cite web|url=http://unxutils.sourceforge.net/|title=Native Win32 ports of some GNU utilities|website=unxutils.sourceforge.net}} and is in IBM i.{{cite web |title=IBM System i Version 7.2 Programming Qshell |language=en |author=IBM |website=IBM |author-link=IBM |url=https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_74/rzahz/rzahzpdf.pdf?view=kc |access-date=2020-09-05 |url-status=live|archive-url=https://web.archive.org/web/20200918130823/https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_74/rzahz/rzahzpdf.pdf?view=kc |archive-date=2020-09-18 }}
Usage
The Single UNIX Specification is: {{code|dirname path}}.
Examples
The command reports the directory path portion of a path ignoring any trailing slashes.
$ dirname /home/martin/docs/base.wiki
/home/martin/docs
$ dirname /home/martin/docs/
/home/martin
$ dirname base.wiki
.
Performance
Since the command accepts only one operand, its usage within the inner loop of a shell script can be detrimental to performance. Consider:
while read file; do
dirname "$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##*/*}" ]; then
echo "."
else
echo "${file%/*}";
fi
Note that these handle trailing slashes differently than {{code|dirname}}.
See also
- {{Annotated link|basename}}
- {{Annotated link|List of POSIX commands}}
References
{{Reflist}}
External links
{{Wikibooks|Guide to Unix|Commands}}
- {{man|cu|dirname|SUS|return the directory portion of a pathname}}
- {{man|1|dirname|die.net}}
- {{man|1|dirname|OpenBSD}}
{{Unix commands}}
{{Core Utilities commands}}