Files and folders

The dirname command

Removes the last segment of a path and returns the folder that contains it.

Syntax

dirname <ruta>Try it in the terminal →

Most useful options

-z, --zeroEnds each output line with a NUL byte instead of a newline. Works well with xargs -0
--helpShows the help and exits
--versionShows the version of the coreutils package it belongs to

Copy-ready examples

$ dirname /usr/bin/folder of a path with a trailing slash; the slash is dropped.

Example output

/usr
$ dirname /var/log/syslogfolder of a file nested inside several folders.

Example output

/var/log
$ dirname stdio.hwithout any slash there is no folder: it returns the dot, which is the current folder.

Example output

.
$ dirname dir1/str dir2/strseveral paths at once, with one output per line.

Example output

dir1
dir2

You can try them in the browser terminal: it does not touch your computer.

Common errors

MessageCauseFix
dirname: missing operandYou ran dirname without any path.Pass the path, for example dirname /path/to/file. To see the help, run dirname --help.

Typical mistakes

  • It works on the text only: it does not check that the folder exists. dirname /noexiste/archivo returns /noexiste without warning.
  • Without slashes it returns a dot, the current folder, not an empty string or an error.
  • A relative path stays relative: dirname a/b gives a, not the absolute path. If you need the absolute one, use realpath.

Differences from similar commands

  • basename: returns the opposite: the last segment. dirname removes that segment and leaves you the folder.
  • realpath: gives the absolute path and checks the links. dirname only trims the text: dirname /noexiste/archivo gives /noexiste without looking at the disk.

Related commands

FAQ

How do I get the folder where a script lives?

With cd "$(dirname "$0")" && pwd: it enters the script's folder and pwd prints its absolute path, wherever you run it from.

What does it return for a folder written with a trailing slash?

The same as without it: dirname /usr/bin/ and dirname /usr/bin both give /usr, because the trailing slash is removed before cutting.

How do I use it with paths that contain spaces?

Quote each path. If you pipe them along, use -z with xargs -0 so the spaces do not split the name.

Learn to actually use it

The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.

Start the free course