LinuxCommandLibrary

basename

Extract filename from a path

TLDR

Show only the file name from a path

$ basename [path/to/file]
copy

Show only the rightmost directory name from a path
$ basename [path/to/directory]
copy

Show only the file name from a path, with a suffix removed
$ basename [path/to/file] [suffix]
copy

SYNOPSIS

basename [OPTION]... NAME[SUFFIX]

PARAMETERS

-a, --multiple
    Process multiple NAME arguments, each producing one output line

-s, --suffix=SUFFIX
    Remove a single trailing occurrence of SUFFIX from each NAME; use with -a for multiples

-z, --zero
    Delimit output lines with NUL instead of newline (for xargs, find -print0)

--help
    Display usage summary and exit

--version
    Output version info and exit

NAME
    Pathname(s) to process; directory prefix stripped

SUFFIX
    Optional trailing suffix to remove from NAME (last match only)

DESCRIPTION

The basename command extracts the base filename from a given pathname by removing all leading directory components (everything before and including the last /) and, optionally, a trailing suffix.

For example, basename /usr/local/bin/script.sh .sh outputs script. If no suffix is provided, it simply removes the directory prefix: basename /home/user/file.txt yields file.txt.

It is a core utility for shell scripts, enabling dynamic filename manipulation without parsing paths manually. Supports processing multiple arguments with -a, specifying suffix separately with -s (compatible with multiples), and NUL-delimited output via -z for safe handling of special characters in filenames.

Edge cases include: paths of just / return /; empty input or no slashes return the input minus suffix if matching; trailing slashes are ignored. It does not resolve symlinks or expand globs—inputs are literal strings.

CAVEATS

Removes only the last occurrence of SUFFIX; literal strings—no glob expansion or symlink following. Paths of only slashes output /. Empty NAME outputs nothing.

EXAMPLES

basename /foo/bar.txtbar.txt
basename /foo/bar.txt .txtbar
basename -s .txt -a file1.txt file2.txtfile1
file2

basename -z /path/filefile (NUL terminated)

EXIT STATUS

0 on success; 1+ if error (invalid options, no input, etc.)

HISTORY

Originated in early Unix (Version 7, 1979); POSIX.1-2008 standardized. GNU version in coreutils since 1990s, actively maintained with portability enhancements.

SEE ALSO

Copied to clipboard