basename - Return non-directory portion of path name

Synopsis

basename string [suffix]

Description

You can use basename to delete any prefix ending with the last slash (/) character present in string, and a suffix, if specified. The resulting filename is written to standard output. The string is processed using the following rules:

  • If string consists entirely of slash characters, a single slash character is written to standard output and processing ends.
  • If there are any trailing slash characters in string, they are removed.
  • If there are any slash characters remaining in string, the prefix of string up to and including the last slash character is removed.
  • If a suffix is specified, and is not identical to the characters remaining in string, and is identical to a suffix of the characters remaining in string, the suffix is removed. Otherwise string is not modified. It is not an error if suffix is not found in string.

Exit status

  • 0 on success
  • >0 if an error occurs.
Examples
  1. Set the shell variable FOO to "trail".
    
    FOO=$(basename /usr/bin/trail)
    
  2. Return the last part of the path "/usr/bin/this_test" with the "test" suffix removed.
    
    basename /usr/bin/this_test test