Basename Command in Linux
2 min read
basename is a command-line utility that strips directory and trailing suffix from given file names.
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:
The output will include the file name:
basename command removes any trailing
Both commands will produce the same output:
By default, each output line ends in a newline character. To end the lines with
NUL, use the
basename command can accept multiple names as arguments. To do so, invoke the command with the
--multiple) option, followed by the list of files separated by space.
basename -a /etc/passwd /etc/shadow
Removing a Trailing Suffix
To remove any trailing suffix from the file name, pass the suffix as a second argument:
basename /etc/hostname name
Generally, this feature is used to strip file extensions:
basename /etc/sysctl.conf .conf
Another way to remove a trailing suffix is to specify the suffix with the
basename -s .conf /etc/sysctl.conf
This syntax form allows you to strip any trailing suffix from multiple names:
basename -a -s .conf /etc/sysctl.conf /etc/sudo.conf
The following example shows how to use the
basename command inside a bash
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" done
If you are using bash as your shell, instead of invoking
basename, you can use strip the trailing extension using Shell Parameter Expansion
basename command strips any leading directory and trailing suffix from the name.
If you have any questions or feedback, feel free to leave a comment.