How To

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.

Cyber Defence

Recent Posts

timeout Command in Linux: Kill Long-Running Commands Safely

The timeout command in Linux runs a command with a time limit and terminates it when the limit is reached. It is part of GNU coreutils, available on virtually every Linux distribution. It is most useful for commands with no built-in timeout option, such as ping, curl, tcpdump, or a custom script that might hang indefinitely. How the timeout Command Works in Linux The syntax is: bashtimeout [OPTIONS] DURATION COMMAND [ARG]...…

7 minutes ago

rmmod Command in Linux: Remove Kernel Modules and Blacklisting

The rmmod command in Linux removes a loaded module from the running kernel. Because the kernel has…

24 hours ago

free Command in Linux: Check Memory Usage and Interpret Output

The free command in Linux gives you a quick summary of RAM and swap usage. It reads…

24 hours ago

diff Command in Linux: Compare Files and Create Patches

The diff command in Linux compares two text files line by line and shows the lines that…

1 day ago

Flush DNS Cache on Windows, Linux, and macOS: Quick Commands

DNS cache is a temporary database your OS and browser build as you browse. Each time you visit a website, the domain-to-IP mapping is saved locally, cutting out the round trip to a remote DNS server on repeat visits. Stale entries are the most common reason to flush the DNS cache: a server moves to a new IP, but your OS or browser still routes to the old address. This guide covers how to clear the DNS cache on Windows, Linux, and macOS, and how to flush the separate cache stored inside Chrome and Firefox. Flush DNS Cache on Windows The command is the same on Windows 10, Windows 11, and earlier supported releases. Open Command Prompt with administrator privileges. Type cmd in the Windows search bar, right-click Command Prompt, and select Run as…

1 day ago

Change User Password in Ubuntu: Command Line and GNOME GUI

Using a strong, unique password for every account is one of the most effective security…

2 days ago