dirname – strip filename from path

dirname command
dirname command

dirname strips the last component (filename) from a path, returning the directory.

Synopsis

dirname PATH

Examples

Get directory from path

$ dirname /var/log/syslog
/var/log

$ dirname /home/greys/documents/report.pdf
/home/greys/documents

Filename only (returns .)

$ dirname report.pdf
.

Multiple paths

$ dirname /path/to/file1 /path/to/file2
/path/to
/path/to

In Scripts

Get script directory

#!/bin/bash
SCRIPT_DIR=$(dirname "$0")
cd "$SCRIPT_DIR"

Absolute script directory

#!/bin/bash
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)

Create file in same directory

input="/data/files/input.csv"
output="$(dirname "$input")/output.csv"
# output = /data/files/output.csv

Shell Alternative

Using parameter expansion:

path="/var/log/syslog"
${path%/*}    # Result: /var/log

Combined with basename

path="/var/log/syslog"
dir=$(dirname "$path")      # /var/log
file=$(basename "$path")    # syslog

echo "File: $file in directory: $dir"

Tips

  • Doesn’t resolve symlinks: Use realpath for that
  • Doesn’t check existence: Works on any string
  • Returns . for plain filenames

See Also

  • basename — Get filename from path
  • realpath — Resolve absolute path
  • pwd — Print working directory

Tutorials