🎁 New User? Get 20% off your first purchase with code NEWUSER20 Register Now →
Menu

Categories

dirname Command

Beginner Shell Scripting man(1)

Strip last component from a file path

👁 9 views 📅 Updated: Mar 15, 2026
SYNTAX
dirname NAME

What Does dirname Do?

dirname strips the last component from a file path, returning the directory portion. It is the complement to basename — dirname gets the directory, basename gets the filename.

dirname is essential in scripts for finding the directory containing a file, navigating relative to a script\'s location, and constructing output paths based on input file locations.

dirname does not check if the path exists — it simply performs string manipulation on the path. For resolving symlinks and getting absolute paths, use readlink -f or realpath.

Options & Flags

OptionDescriptionExample
PATH Extract directory from path dirname /var/log/syslog
-z End output with NUL instead of newline dirname -z /path/to/file
multiple Process multiple paths dirname /a/b/c /x/y/z

Practical Examples

#1 Get directory from path

Returns the directory containing the file.
$ dirname /var/log/nginx/access.log
Output: /var/log/nginx

#2 Find script directory

Gets the directory where the current script is located.
$ SCRIPT_DIR=$(dirname "$0")

#3 Navigate relative to script

Sources a config file from the same directory as the script.
$ source "$(dirname "$0")/config.sh"

#4 Process file in same directory

Uses dirname to construct output path relative to input file.
$ OUTPUT_DIR=$(dirname "$INPUT_FILE"); cp "$INPUT_FILE" "$OUTPUT_DIR/backup/"

#5 Multiple paths

Returns directory for each path.
$ dirname /usr/bin/python3 /etc/nginx/nginx.conf
Output: /usr/bin /etc/nginx

#6 Relative paths

Works with relative paths too.
$ dirname ./src/main.py
Output: ./src

Tips & Best Practices

Script location pattern: SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) gives the absolute directory of the running script. Very common pattern.
dirname is string manipulation: dirname does not check if paths exist. dirname /nonexistent/path/file returns /nonexistent/path.
Trailing slashes: dirname handles trailing slashes: dirname /a/b/ returns /a. But edge cases exist — test your specific usage.

Frequently Asked Questions

How do I get the directory of the current script?
Use SCRIPT_DIR=$(dirname "$0"). For absolute path: SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd).
What is the difference between dirname and basename?
dirname returns the directory part (/var/log from /var/log/syslog). basename returns the file part (syslog from /var/log/syslog).
Does dirname check if the path exists?
No — dirname performs string manipulation only. It does not access the filesystem.

Master Linux with Professional eBooks

Curated IT eBooks covering Linux, DevOps, Cloud, and more

Browse Books →