Linux Command Reference ยท Files and Directories
Linux dirname command
Reference for the Linux dirname command: print the directory part of a path, edge cases like trailing slashes and bare names, and finding a script's directory.
dirname prints a path with its last component removed: dirname /var/log/syslog prints /var/log. If the path has no slash at all, the answer is ., the current directory. Like basename, it works on text only and never checks that the path exists.
Its most common use is in scripts that need to know in which directory they live, so that they can load sibling files no matter where they were started from.
dirname [OPTION] NAME...
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
dirname [-z] NAME...
| Name | Description |
|---|---|
NAME |
One or more paths. Each result is printed on its own line. |
-z, --zero |
End each output line with NUL instead of a newline. |
Returns: the directory part on standard output; exit status 0, or non-zero when called without operands.
Usage notes
- Rules in order: trailing slashes are removed, then the last component is removed, then trailing slashes left behind are removed. If nothing remains, the answer is
.for relative paths and/for absolute ones. - No slash means
.:dirname file.txtis., meaning "this directory". It does not print an empty line. - An empty string gives
.in GNU coreutils. - It does not resolve anything:
dirname link/..islink, with no regard for symlinks. For a real directory userealpathorcd ... && pwd -P. - Script directory idiom:
$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)gives an absolute directory, even if the script is sourced or started with a relative path. Use$0only for scripts that are never sourced;BASH_SOURCE[0]is correct in both cases. If the script itself may be a symlink, applyreadlink -ffirst. - Quote everything:
dirname -- "$path"handles spaces and leading dashes. Unquoted use splits on whitespace. - Performance: each call starts a process. Inside tight loops use
${path%/*}, which is fast but returns the whole string for a bare name (${file%/*}offile.txtisfile.txt), so it only matchesdirnamewhen the path contains a slash. - Creating output directories:
mkdir -p "$(dirname "$target")"before writing$targetis a classic use. - Several arguments are supported in modern coreutils; very old systems accept only one.
Related
basename,realpath,readlink,pwd,mkdir- Lessons: Parameter expansion, First script