WebMasterCampus
WEB DEVELOPER Resources

Linux basename Command

Learn Linux basename Command with examples


Linux basename Command

In Linux, we can use “basename” command prints the last element of a file path. Optionally, It can also delete any following suffix if needed.

The “basename” takes a filename and prints the filename’s last portion.

basename Command Syntax

>> basename NAME [SUFFIX]
>> basename OPTION... NAME... 

basename Command Example

>> basename /etc/passwd

passwd

basename Command Removes Trailing slash

The basename command removes any trailing / characters.

>> basename /etc/ssh
>> basename /etc/ssh/

ssh
ssh

basename -z Command

By default, each output line ends in a newline character. To end the lines with NUL, use the -z (–zero) option.

>> basename -z /etc/passwd

passwd >>

basename Second Argument to Remove a Trailing Suffix

To remove any trailing suffix from the file name, pass the suffix as a second argument.

Usually, we use this feature to strip file extensions.

>> basename /etc/hostname name

host
>> basename /etc/sysctl.conf .conf

sysctl

basename -s Command (to Remove Suffix)

To remove a trailing suffix we can also use the suffix with the -s (–suffix=SUFFIX) option.

>> basename -s .conf /etc/sysctl.conf

sysctl

basename -a Command Remove Suffix Multiple Files

basename -a allows you to strip any trailing suffix from multiple names.

>> basename -a -s .conf /etc/sysctl.conf /etc/sudo.conf

sysctl
sudo

Use basename Command inside Bash Shell Script

The basename command inside a bash shell script 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” done

basename Command in Linux (Documentation)

~$ man basename

NAME
       basename - strip directory and suffix from filenames

SYNOPSIS
       basename NAME [SUFFIX]
       basename OPTION... NAME...

DESCRIPTION
       Print NAME with any leading directory components removed.  If specified, also remove a trailing SUFFIX.

       Mandatory arguments to long options are mandatory for short options too.

       -a, --multiple
              support multiple arguments and treat each as a NAME

       -s, --suffix=SUFFIX
              remove a trailing SUFFIX; implies -a

       -z, --zero
              end each output line with NUL, not newline

       --help display this help and exit

       --version
              output version information and exit
EXAMPLES
       basename /usr/bin/sort
              -> "sort"

       basename include/stdio.h .h
              -> "stdio"

       basename -s .h include/stdio.h
              -> "stdio"

       basename -a any/str1 any/str2
              -> "str1" followed by "str2"
Created with love and passion.