LinuxCommandLibrary
GitHubF-DroidGoogle Play Store

dirname

directory path extraction utility

TLDR

Get directory path
$ dirname [/path/to/file.txt]
copy
Multiple paths at once
$ dirname [/path/one/file1] [/path/two/file2]
copy
NUL-separated output (for scripting)
$ dirname -z [/path/to/file]
copy

SYNOPSIS

dirname path...

DESCRIPTION

dirname extracts the directory portion of a pathname, removing the last component. It's commonly used in shell scripts to find the directory containing a file or script.The command is the complement to basename.

PARAMETERS

-z, --zero

Separate output with NUL instead of newline

BEHAVIOR

Given `/path/to/file.txt`:- dirname returns `/path/to`Given `/path/to/`:- dirname returns `/path`Given `file.txt`:- dirname returns `.`Given `/`:- dirname returns `/`

WORKFLOW

$ # Get directory
dirname /usr/local/bin/command
# Output: /usr/local/bin

# Get parent of current script
SCRIPT_DIR=$(dirname "$0")

# Get absolute path to script directory
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)

# Multiple files
dirname /path/to/file1 /path/to/file2

# In scripts
cd "$(dirname "$0")"  # Change to script's directory
copy

COMMON USES

Script directory:

$ #!/bin/bash
SCRIPT_DIR=$(dirname "$0")
source "$SCRIPT_DIR/config.sh"
copy
Parent directory:
$ parent=$(dirname "/path/to/file")
copy
Multiple levels:
$ # Go up two directories
grandparent=$(dirname "$(dirname "/path/to/file")")
copy

INSTALL

sudo apt install coreutils
copy
sudo dnf install coreutils
copy
sudo pacman -S coreutils
copy
sudo apk add coreutils
copy
sudo zypper install coreutils
copy
brew install coreutils
copy
nix profile install nixpkgs#coreutils
copy

CAVEATS

Doesn't resolve symbolic links (use readlink). Doesn't check if path exists. Trailing slashes affect output. Doesn't handle all edge cases (empty strings, etc.). Path doesn't need to exist.

HISTORY

dirname has been part of Unix since the early days, included in POSIX standards alongside basename.

SEE ALSO

RESOURCES

Braincup
Open source brain training for math, memory and focus
Braincup mini-games
41 mini-games · Apache-2.0
No ads · No tracking
Play in browser
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid
276 stars
From the maker of Linux Command Library
Copied to clipboard
Braincup
Open source brain training for math, memory and focus. 41 mini-games, from mental arithmetic to Sudoku, N-Back and Solo Chess.
Apache-2.0 licensed · No ads · No tracking · No account
From the maker of Linux Command Library
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid