Skip to content

dirname Command: Extracting Directory Names

Summary

The dirname command extracts the directory portion of a given file name or path. It's useful for scripts where you need to work with the directory containing a file, rather than the file itself.

Introduction

The dirname command is a simple but powerful tool in Linux used to strip the last component from a file name. It essentially returns the path to the directory that contains the specified file or directory. This can be incredibly useful in shell scripts for determining where a script is located, manipulating file paths, and managing directories.

Use case and Examples

Extracting the Directory of a File

dirname /home/user/documents/report.txt
This command will output /home/user/documents. It takes the full path to the report.txt file and returns the directory in which it resides.

Extracting the Directory of a Directory

dirname /usr/local/bin
This command will output /usr/local. It works equally well with directories, returning the parent directory.

Using with Relative Paths

dirname ./my_script.sh
This command will typically output ., representing the current directory. The dirname command works with relative paths as well.

Handling Multiple Arguments

dirname /path/to/file1.txt /another/path/to/file2.txt
This command will output:
/path/to
/another/path/to
dirname can take multiple arguments, processing each one separately and printing the results on separate lines.

Using with Variable Expansion

FILE_PATH="/var/log/syslog"
DIRECTORY=$(dirname "$FILE_PATH")
echo "The directory is: $DIRECTORY"
This demonstrates how dirname can be used within a script to extract the directory from a variable containing a file path. The script then prints the extracted directory.

Commonly used flags

Flag Description Example
--help Displays help information and exits. dirname --help
--version Displays version information and exits. dirname --version
-z, --zero Output a zero byte (ASCII NUL) instead of a newline character at the end of each output line. This is useful when piping the output to commands like xargs -0. dirname /path/to/file -z | xargs -0 rm -rf


Share on Share on

Comments