Skip to content
Related Articles
Get the best out of our app
Open App

Related Articles

basename Command in Linux with examples

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

basename strips directory information and suffixes from file names i.e. it prints the file name NAME with any leading directory components removed.

Using basename command :

The basename command can be easily used by simply writing basename followed by the file name or the full pathname.

Syntax of basename command :

$basename NAME [SUFFIX]
$basename OPTION NAME

where, NAME refers to the file name or file full pathname and OPTION refers to the options compatible with the basename command and in case, if you want to strip off the suffix of a file you can give the filename followed by the SUFFIX name you want to get rid off.

Example :

/* basename removes directory path and 
   returns the file name, kt */
$basename /usr/local/bin/kt

In the first case, the basename command removes the directories name from the full path name given of file kt and in the second case basename removes the suffix .html from kt.html.

Options for basename command :

  • -a, – -multiple option : This option lets you support multiple arguments and treat each as a NAME i.e you can give multiple file names or full path names with the use of -a option.
    /* -a is used for multiple inputs */
    $basename -a /usr/local/bin/kt /usr/local/bin/kt.html
  • -s, – -suffix = SUFFIX option : This option removes a trailing suffix SUFFIX,such as a file extension.
    /*.html suffix is removed from kt.html 
       when followed by -s option */
    $basename -s .html kt.html
  • -z option : This separates the output with NULL rather than a newline.
    /* The outputs of the two arguments passed
       are not separated by a newline*/
    $basename -az /usr/local/bin/kt kt.html
  • – -help option : This displays the help information and exit.
  • – -version option : This displays the version information and exit.

Application of basename command :

There are many utilities available which are only useful when it comes to shell scripts and doesn’t have any practical application when used by itself and basename comes under this category.

Example of a shell script which converts gif image files into png image files with the help of basename command :

/*shell script to convert the
gif image file format into
png image file format */

for file in *.gif;do
    #exit if there are no files
    if [! -f $file];then
    b='basename $file .gif'
    echo NOW $b.gif is $b.png
    giftopnm $b.gif | pnmtopng >$b.png

In the above shell script basename command is used to extract the file names with extension .gif without the extension so that they can be converted into .png files.

References : basename command

My Personal Notes arrow_drop_up
Last Updated : 03 Oct, 2022
Like Article
Save Article
Similar Reads