basename

Strip directory and suffix from filenames

Syntax
      basename string [suffix]

      basename [-a] [-s suffix] string [...]

Key
   -a   Treat every argument as a string
        (as if basename were invoked with just one argument)

   -s   The suffix is taken as its argument, all other arguments are treated as a string.

The basename utility deletes any prefix ending with the last slash / character present in string (presumably a filename), after first stripping any trailing slashes, and a suffix, if given. The suffix is not stripped if it is identical to the remaining characters in string. The resulting filename is written to the standard output.

MacOS is not case sensitive and basename does not consult the file system to see if the case is correct or even that the path exists at all.

A non-existent suffix is ignored.

basename will exit 0 on success, and >0 if an error occurs.

Examples

Set the shell variable FOO to /usr/bin

$ FOO=`dirname /usr/bin/trail`
$ echo $FOO
/usr/bin/

Set the shell variable FOO to the basename of iMovie.app:

$ FOO=`basename /Applications/imovie.app`
$ echo $FOO
imovie.app

For each of the files found in directoryA delete the matching files from directoryB:

$ for file in directoryA /*; do rm directoryB /`basename $file`; done

“Then I came up with this crazy idea just to walk out on the stage with no band at all and just start singing whatever came to mind. I actually fought the idea for a while because it seemed almost too radical, but it became obvious what I was supposed to be doing” ~ Bobby McFerrin

Related macOS commands

dirname – return filename or directory portion of pathname.
ls - List information about file(s).
Equivalent Windows command: Variable Substring


 
Copyright © 1999-2024 SS64.com
Some rights reserved