dirname - extract the directory name from a full path

Hi! If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

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


Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Fark
  • Furl
  • Netscape
  • Reddit
  • Smarking
  • Spurl
  • StumbleUpon
  • Technorati
  • YahooMyWeb

1 comment so far ↓

#1 basename - strip directory and suffix from a full path to a file | Unix Commands on 05.06.08 at 8:52 am

[...] ← dirname - extract the directory name from a full path [...]

Leave a Comment