Home > File & Directory Management > dirname

Guide to the dirname Command

The `dirname` command is used to extract the directory path without the file name from a given file path. It is particularly useful in shell scripts when referencing other files or directories based on the location of a file.

Main Options

The `dirname` command is very simple and has very few complex options. It is mainly used alone or with the `-z` option.

1. Basic Usage

Generated command:

Try combining the commands.

Description:

`dirname` Executes the command.

Combine the above options to virtually execute commands with AI.

Commonly Used Examples

The `dirname` command is used in various scripts that handle file paths. Learn the basic usage through the examples below.

Extracting Basic Directory Path

dirname /home/user/documents/file.txt

Outputs the directory path excluding the file name from the file path.

Extracting Current Directory Path

dirname file.txt

If there is no file name, it outputs the current directory, which is '.'.

Extracting Root Directory Path

dirname /

Running `dirname` on the root directory `/` will output `/`.

Usage in Shell Scripts

SCRIPT_DIR=$(dirname "$0")
CONFIG_FILE="$SCRIPT_DIR/config.ini"
echo "Configuration file path: $CONFIG_FILE"

It is useful when referencing other files based on the location of the current script file.

dirname vs basename

`dirname` and `basename` perform opposing functions and are essential for handling file paths.

  • dirname: Extracts only the directory path from the file path. (e.g., `/home/user/documents`)
  • basename: Extracts only the file name from the file path. (e.g., `file.txt`)

Related commands

These are commands that are functionally similar or are commonly used together.


Same category commands