Unix: Find Directory Name From Path

Posted on in Categories , , , last updated April 7, 2014

I am a new Unix shell programer. How can I extract the directory name from a full path (say /nas01/data/backups/file.tar.gz)? How do I get directory name from its path on a Linux or Unix-like system?

You need to use the ”dirname” command[/donotprint]In other words, you can extract the directory name using dirname command.

Method #1: Use dirname command to get directory name

The syntax is:

dirname /path/to/file


VAR=”$(dirname /path/to/my/myname.txt)”


OUT="$(dirname ${FOO})"


The following example displays output /nas01/data/backups:

dirname /nas01/data/backups/file.tar.gz

Sample outputs:


The following line sets the shell variable SRC to /nas01/data/backups:

SRC="$(dirname /nas01/data/backups/file.tar.gz)"
echo "Dirpath - $SRC"

Sample outputs:

Dirpath - /nas01/data/backups

Method #2: Extract the directory name from a full path using bash/ksh shell

The $ character is used for parameter expansion, and command substitution. You can use it for manipulating and/or expanding variables on demands without using external commands such as sed or awk. To remove from shortest rear (end) pattern:


In this example, set FILE to /nas01/data/backups/demo.avi:

echo "\$FILE = $FILE"

To extract the directory name, type:

echo "${FILE%/*}"
# OR store to DIR #
echo "Dirpath - $DIR"

Sample outputs:

Dirpath - /nas01/data/backups

See man pages dirname(1), bash(1), ksh(1) for more info.

1 comment

Leave a Comment