Cybersecurity Updates & Tools

basename Command in Linux: Strip Directory Paths and Suffixes

The basename command in Linux extracts the last component of a file path, removing the leading directory portion and an optional trailing suffix. It is a POSIX-standard utility, part of GNU coreutils, and available on every Linux distribution.

This guide covers how to use basename with practical examples and when to use Bash parameter expansion instead.

How to Use the basename Command in Linux

The basic syntax is:

bashbasename NAME [SUFFIX]

The most common use is stripping the directory path from a full path:

bashbasename /etc/passwd
passwd

basename removes trailing slashes before processing, so both of the following produce the same result:

bashbasename /usr/local/basename /usr/local
local

The complementary command is dirname, which returns everything except the last component. Running dirname /etc/passwd returns /etc. Together, they decompose any path into its two parts without reading the filesystem.

Strip Suffixes and Process Multiple Paths

To strip a suffix, pass it as a second argument:

bashbasename /etc/sysctl.conf .conf
sysctl

The suffix is a plain string match against the end of the name, not a glob or regex. It must appear at the very end to be removed: basename report_final.txt _final.txt returns report.

Use the -s flag to strip a suffix when processing multiple paths with -a. The positional syntax only works with a single path — -s is required for the combination:

bashbasename -a -s .conf /etc/sysctl.conf /etc/sudo.conf
sysctlsudo

NUL-terminated output. By default, each result ends with a newline. Use -z to terminate with a NUL character instead, which is safe for piping to xargs -0. This handles filenames containing spaces or special characters without breaking the pipeline:

bashbasename -az -s .conf /etc/sysctl.conf /etc/sudo.conf | xargs -0 echo
sysctl sudo

Using basename in Scripts and Bash Alternatives

basename is common in shell scripts that rename or process files. The mv -- "$file" pattern protects against filenames starting with - being misread as flags:

bashfor file in *.jpeg; do    mv -- "$file" "$(basename "$file" .jpeg).jpg"done

Use Bash parameter expansion in large loops. Each call to basename forks a subprocess. In a loop over thousands of files, that overhead accumulates. The % operator strips the shortest suffix matching a pattern entirely inside the current shell:

bash${filename%.*}    # removes the file extension${filename%.jpeg} # removes .jpeg specifically

This is significantly faster than calling basename per file and produces identical results.

Use basename on the command line for quick path manipulation. In Bash scripts with large loops, ${filename%.*} is faster and avoids the subprocess overhead. Leave a comment below if you run into any issues.