[ Bottom of Page | Previous Page | Next Page | Contents | Index | Library Home | Legal | Search ]

Commands Reference, Volume 2

dirname Command

Purpose

Writes to standard output all but the last part of a specified path.

Syntax

dirname Path

Description

The dirname command reads the specified path name, deletes all but the last / (slash) and the characters following it, and writes the result to standard output. If no characters follow the last /, the dirname command uses the next to last / and ignores all characters following it. The dirname command applies the following rules in creating the path name:

  1. If the Path parameter is a // (double slash), or if the Path parameter consists entirely of slash characters, change the string to a single / (slash). Skip steps 2 through 7.
  2. Remove any trailing / characters from the specified path.
  3. If there are no / characters remaining in the Path parameter, change the path to a single (period). Skip steps 4 through 7.
  4. Remove any trailing, non-slash characters from the path.
  5. If the remaining path is // (double slash), go to step 6.
  6. Remove any trailing slash characters from the path.
  7. If the remaining path is empty, change the path to a single /.

For example, entering:

dirname // 

results in a single / (slash). Entering:

dirname /a/b/ 

results in /a. Entering:

dirname a 

results in a single . (period). Entering:

dirname a/b 

results in the path name a.

The dirname and basename commands are generally used inside command substitutions within a shell procedure to specify an output file name that is some variation of a specified input file name.

Exit Status

This command returns the following exit values:

0 Successful completion
>0 An error occurred.

Examples

To construct the name of a file located in the same directory as another, enter:

AOUTFILE=`dirname $TEXTFILE`/a.out

This sets the shell variable AOUTFILE to the name of an a.out file that is in the same directory as TEXTFILE. If TEXTFILE is /home/fran/prog.c, the value of dirname $TEXTFILE is /home/fran and AOUTFILE becomes /home/fran/a.out.

Files

/usr/bin/dirname Contains the dirname command.

Related Information

The basename command, sh command.

[ Top of Page | Previous Page | Next Page | Contents | Index | Library Home | Legal | Search ]