3 UNIX / Linux basename Command Examples

What is basename?
3 basename examples
Syntax and Options
Related Commands

What is basename?

When you provide a string that contains a filename will full path, basename will remove only the directory portion of it, and return only the filename portion of that string. It can also remove the file extension, and return only the filename without an extension.

3 basename Examples

1. Basename when no file extension

Basename removes the path and displays only the filename. For example, the basename of /etc/passwd is “passwd” as shown below.

$ basename /etc/passwd
passwd

2. Basename when there is a file extension

When the filename contains an extension, basename by default will remove the path and return the filename with the extension

$ basename /usr/local/apache2/conf/httpd.conf
httpd.conf

3. Get only the filename without extension

If you want to get only the filename with the extension, you should pass the extension as 2nd argument to the basename command as shown below. The following example will return only httpd, as the 2nd argument to the basename command is .conf

$ basename /usr/local/apache2/conf/httpd.conf .conf
httpd

Syntax and Options

Syntax:

basename NAME [SUFFIX]
basename OPTION

Explain the option of the basename command. e.g. of chmod shown below.

Short Option Long Option Option Description
–help Shows the help page
–version shows the version of basename command


Related Commands

dirname
readlink

Comments on this entry are closed.

  • Anoop Sharma January 19, 2013, 11:22 pm

    Hi,

    when i trying basename command, i get file name with :command not found as post fix.Please help me. how i can remove ‘:command not found’.

    command
    $basename AS_25201303 25201303

    Output :-
    AS_ :command not found

  • streamlinehost April 2, 2014, 2:36 pm

    add quotes around ‘ AS_25201303’ will make it work:

    basename ‘AS_25201303’ 25201303
    AS_