dirname – extract the directory name from a full path

dirname is a very simple but useful Unix command which is used mostly in shell scripting. Taking a full path to a file as a parameter, it then stips the filename off and returns you just the directory name.

How to use dirname command

This is how dirname is invoked:

ubuntu$ dirname /etc/network/if-down.d/postfix
/etc/network/if-down.d

dirname in shell scripting

The obvious use of dirname command is shown below. This script, based on the full path to a file, prints the parent directory name and a list of all the files in this directory:

#!/bin/bash
FILE=$1
DIR=`dirname $FILE`
FILES=`ls $DIR`

echo "Filename specified: $FILE"
echo "Parent directory: $DIR"

for f in $FILES; do
echo "- $f"
done

See also:

  • basename – strip directory and suffix from a full path to a fil
  • cd – change directory
  • pwd – confirm the current directory you’re in