basename is a command-line utility that strips directory and trailing suffix from given file names.
The basename command supports two syntax formats:
basename NAME [SUFFIX] basename OPTION... NAME...
basename takes a filename and prints the last component of the filename. Optionally, it can also remove any trailing suffix. It is a simple command that accepts only a few options.
The most basic example is to print the file name with the leading directories removed:
basename /etc/passwd
The output will include the file name:
passwd
The basename command removes any trailing / characters:
basename /usr/local/basename /usr/local
Both commands will produce the same output:
basename
By default, each output line ends in a newline character. To end the lines with NUL, use the -z (–zero) option.
The basename command can accept multiple names as arguments. To do so, invoke the command with the -a (–multiple) option, followed by the list of files separated by space.
For example, to get the file names of /etc/passwd and /etc/shadow you would run:
basename -a /etc/passwd /etc/shadow
passwd shadow
To remove any trailing suffix from the file name, pass the suffix as a second argument:
basename /etc/hostname name
host
Generally, this feature is used to strip file extensions:
basename /etc/sysctl.conf .conf
sysctl
Another way to remove a trailing suffix is to specify the suffix with the -s (–suffix=SUFFIX) option:
basename -s .conf /etc/sysctl.conf
sysctl
This syntax form allows you to strip any trailing suffix from multiple names:
basename -a -s .conf /etc/sysctl.conf /etc/sudo.conf
sysctl sudo
The following example shows how to use the basename command inside a bash for loop to rename all files ending with “.jpeg” in the current directory by replacing the file extension from “.jpeg” to “.jpg”:
for file in *.jpeg; do
mv -- "$file" "$(basename $file .jpeg).jpg"
doneIf you are using bash as your shell, instead of invoking basename, you can use strip the trailing extension using Shell Parameter Expansion .
The basename command strips any leading directory and trailing suffix from the name.
At NexonHost, we believe that everyone deserves to have their services and applications be fast, secure, and always available.
Be the first who gets our daily news and promotions directly on your email.
Copyright © 2025 . All Rights Reserved To NexonHost.