Archives and disk tools

Linux commands: dirname

Learn how the Linux dirname command returns the directory portion of a path, so dirname /Users/flavio/test.txt gives you back the /Users/flavio folder.

8 minute lesson

~~~

dirname removes the final path component and prints the directory portion:

Running

dirname /Users/flavio/test.txt

prints /Users/flavio:

Terminal showing dirname /Users/flavio/test.txt command output: /Users/flavio

It manipulates the path string. It does not check whether the file or directory exists:

dirname /a/path/that/does/not/exist.txt
# /a/path/that/does/not

This makes it useful in scripts. For example, find the directory containing a script:

script_dir=$(dirname "$0")
printf 'started from %s\n' "$script_dir"

Quote path variables so spaces do not split one path into several arguments. Also remember that $0 may be relative and may point through a symbolic link; robust script-location code may need to resolve those details.

dirname file.txt prints ., meaning the parent is the current directory. A trailing slash is normalized, so dirname /srv/app/ returns /srv rather than /srv/app.

The companion command basename /Users/flavio/test.txt returns test.txt. Together they separate a path into its directory and final name.

Try it with an absolute path, a relative path, a filename with spaces, and a path ending in /. Predict each result before running it.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →