Unix: Find Directory Name From Path

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
Tutorial details
Difficulty Easy (rss)
Root privileges No
Requirements None
Time 2m
[/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

OR

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

OR

FOO="/path/to/my/folder/filename.avi"
OUT="$(dirname ${FOO})"

Examples

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

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

Sample outputs:

/nas01/data/backups

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:

${VAR%/*}
VAL="${PATHNAME%/*}"

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

FILE="/nas01/data/backups/demo.avi"
echo "\$FILE = $FILE"

To extract the directory name, type:

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

Sample outputs:

Dirpath - /nas01/data/backups

See man pages ksh(1) for more info.

🐧 If you liked this page, please support my work on Patreon or with a donation.
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
1 comment… add one
  • Nicholas Lee Fagan Sep 21, 2014 @ 1:00

    Great tip. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.