How to Extract Directory Paths Using the dirname Command in Linux

When you are writing bash scripts to automate file management, you often have to deal with massive, complex absolute file paths (e.g., /var/www/html/website/public/images/logo.png). If your script only needs to know the name of the final folder holding the file (so it can calculate where to move it), attempting to mathematically slice that string using complex grep or sed commands is a nightmare. To instantly strip away the actual file name and output only the parent directory path, you must use the dirname command.

How the dirname Command Works

The dirname command is a dedicated string parsing utility. It does not actually interact with the hard drive, and it does not check if the file path you give it actually exists. It simply reads a string of text, finds the final forward-slash (/), chops off everything to the right of it, and prints the remaining path.

To extract the directory from our logo path, open your terminal and run:

dirname /var/www/html/website/public/images/logo.png

The command instantly strips the logo.png file off the end of the string and outputs the clean directory path:

/var/www/html/website/public/images

Using dirname in Bash Scripts

The dirname command is almost entirely used inside shell scripts, usually combined with variable substitution. It is incredibly useful for writing scripts that need to operate inside their own relative folder structure, regardless of where the user accidentally downloaded the script.

For example, if you place a variable inside a bash script like this:

CURRENT_DIR=$(dirname "$0")

The $0 variable represents the absolute path of the script itself that is currently running. If the script is running from /home/john/downloads/installer.sh, the dirname command strips away the installer.sh text, and sets the CURRENT_DIR variable strictly to /home/john/downloads. The script now dynamically knows exactly what folder it lives in, allowing it to safely extract accompanying zip files or create configuration folders right next to itself.

Stripping Multiple Levels

By default, dirname only strips the final suffix. However, if you are deep inside a folder structure and you need to jump back two or three levels to find the root directory, you do not need to write a messy loop.

You can run the dirname command against its own output by nesting it, or simply chaining it sequentially.

dirname $(dirname /var/www/html/website/public/images/logo.png)

The inner command strips away the logo.png file. The outer command takes the resulting string, targets the final images folder, strips that away, and cleanly outputs /var/www/html/website/public.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.