basename
Extract filename from a path
TLDR
Show only the file name from a path
Show only the rightmost directory name from a path
Show only the file name from a path, with a suffix removed
SYNOPSIS
basename NAME [SUFFIX]
basename OPTION... NAME...
PARAMETERS
--help
Display a help message and exit.
--version
Output version information and exit.
DESCRIPTION
basename is a command-line utility designed to extract the non-directory portion of a pathname, effectively providing just the filename or the last component of a path. It's an indispensable tool in shell scripting for manipulating file paths, isolating filenames for processing, or displaying in logs. The command can optionally remove a specified SUFFIX from the extracted filename if it matches the trailing part. For example, 'basename /usr/local/bin/program.sh' will output 'program.sh', and 'basename /usr/local/bin/program.sh .sh' will yield 'program'. This utility is often used in conjunction with its counterpart, dirname, to separate a full path into its directory and file components, providing robust path manipulation capabilities within scripts and command-line operations.
CAVEATS
When NAME consists solely of directory separators (e.g., '/', '//', '///'), basename will print a single '/'. If SUFFIX is identical to the extracted base NAME (e.g., 'basename .bashrc .bashrc'), the result will be a single period ('.') signifying the current directory.
MULTIPLE ARGUMENTS PROCESSING
When basename is invoked with multiple NAME arguments (e.g., 'basename file1 file2 file3'), it processes each argument independently. The base name for each argument is then printed on a new line. This mode does not support the optional SUFFIX argument, as it would apply to all files universally.
SUFFIX REMOVAL LOGIC
The optional SUFFIX argument is removed only if it matches the end of the NAME string after any leading directory components have been stripped. The suffix must be an exact match to the trailing characters. If the NAME ends with a directory separator, the suffix is not considered (e.g., 'basename /foo/bar/ .bar' still outputs 'bar').
HISTORY
The basename utility has been a standard part of Unix and Unix-like operating systems for many years. It is typically included in the GNU Core Utilities package on Linux systems, reflecting its fundamental role in shell scripting and file path manipulation. Its design is simple and effective, remaining consistent across various Unix implementations over decades.