[Previous] [Contents] [Next]

basename

Return nondirectory portion of pathname (POSIX)

Syntax:

 basename string [suffix]

Options:

string
A string of text.
suffix
A string of text.

Description:

The basename utility is useful primarily for extracting the filename portion of a pathname, but since it performs only string operations, it can be used with any string.

The basename utility prints to standard output a substring of its string argument, plus a newline character. The basename utility forms this substring by doing the following, in order:

  1. discarding any trailing slash (/) characters
  2. deleting from the pathname all characters up to and including the last slash character in the string argument
  3. deleting the string argument's suffix, provided you've specified a suffix operand that's identical to the string operand's suffix.

    If suffix is equal to the remaining string, the suffix won't be removed (e.g. if suffix is prog.c and the remaining string is prog.c, the suffix .c isn't removed).

The result may be a null string only if string is a null string (""). In this case, basename outputs a single newline character.

If string consists entirely of slash characters, basename prints a single slash, followed by a newline character.

You'll use the basename utility most often within shell scripts, where it's normally invoked inside back-tick (`...`), or contained in $(...).

Examples:

Command: Output:
basename . .
basename /usr/src/prog.c prog.c
basename /usr/src/prog.c .c prog
basename /usr/src/prog.c .a prog.c
basename /usr/src/ src
basename ...//[fred] [fred]

Files:

The basename utility writes the basename string derived from the command-line parameters to its standard output.

Exit status:

0
Successful completion.
>0
An error occurred.

See also:

awk, dirname, fullpath


[Previous] [Contents] [Next]