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

Commands Reference, Volume 1

basename Command

Purpose

Returns the base file name of a string parameter.

Syntax

basename StringSuffix ]

Description

The basename command reads the String parameter, deletes any prefix that ends with a / (slash) and any specified Suffix parameter, and writes the remaining base file name to standard output. The basename command applies the following rules in creating the base file name:

  1. If the String parameter is a // (double slash), or if the String parameter consists entirely of slash characters, change the string to a single / (slash). Skip steps 2 through 4.
  2. Remove any trailing / characters from the specified string.
  3. If there are any / characters remaining in the String parameter, remove the prefix of the string up to and including the last / character.
  4. If a Suffix parameter is specified and is identical to the characters remaining in the string, the string is not modified. For example, entering:

    K > basename /u/dee/desktop/cns.boo cns.boo

    results in:

    cns.boo

    If a Suffix parameter is specified and is not identical to all the characters in the string but is identical to a suffix in the string, the specified suffix is removed. For example, entering:

    K > basename /u/dee/desktop/cns.boo .boo

    results in:

    cns

    Failure to find the specified suffix within a string is not considered an error.

The basename and dirname commands are generally used inside command substitutions within a shell script 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

  1. To display the base name of a shell variable, enter:

    basename $WORKFILE

    The command displays the base name of the value assigned to the shell variable WORKFILE. If the value of the WORKFILE variable is the /home/jim/program.c file, then the command displays program.c.

  2. To construct a file name that is the same as another file name, except for its suffix, enter:

    OFILE=`basename $1 .c`.o

    This command assigns to the OFILE file the value of the first positional parameter ($1), but with its .c suffix changed to .o. If $1 is the /home/jim/program.c file, OFILE becomes program.o. Because program.o is only a base file name, it identifies a file in the current directory.

    Note: The ` (grave accent) specifies command substitution.

Files

/usr/bin/basename Contains the basename command.

Related Information

The dirname command, sh command.

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