Skip to content
Tutorials Center
My learning

Topics

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.

Terminal
dirname [OPTION] NAME...

Try it

Bash Edge cases

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.

Bash Finding the script directory and building paths

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

Terminal
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.txt is ., meaning "this directory". It does not print an empty line.
  • An empty string gives . in GNU coreutils.
  • It does not resolve anything: dirname link/.. is link, with no regard for symlinks. For a real directory use realpath or cd ... && 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 $0 only for scripts that are never sourced; BASH_SOURCE[0] is correct in both cases. If the script itself may be a symlink, apply readlink -f first.
  • 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%/*} of file.txt is file.txt), so it only matches dirname when the path contains a slash.
  • Creating output directories: mkdir -p "$(dirname "$target")" before writing $target is a classic use.
  • Several arguments are supported in modern coreutils; very old systems accept only one.