This tutorial explains Linux “basename” command, options and its usage with examples.
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.
The basename command applies the following rules in creating the base file name:
1. If the String parameter is a // (double slash), or if the String parameter consists entirely of slash characters, change the string to a single / (slash). Skip steps 2 through 4.
2. Remove any trailing / characters from the specified string.
3. If there are any / characters remaining in the String parameter, remove the prefix of the string up to and including the last / character.
4. If a Suffix parameter is specified and is identical to the characters remaining in the string, the string is not modified. For example, entering:
K > basename /u/dee/desktop/cns.boo cns.boo
If a Suffix parameter is specified and is not identical to all the characters in the string but is identical to a suffix in the string, the specified suffix is removed. For example, entering:
K > basename /u/dee/desktop/cns.boo .boo
Failure to find the specified suffix within a string is not considered an error.
The basename and dirname commands are generally used inside command substitutions within a shell script to specify an output file name that is some variation of a specified input file name.
basename [string] [suffix]
string – The leading part of the path name or string.
suffix – Additional remaining portion of name that if matches will be removed.
This command returns the following exit values:
An error occurred.
1. Basename when no file extension
$ 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
f 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.
$ basename /usr/local/apache2/conf/httpd.conf .conf httpd
Sanfoundry Global Education & Learning Series – 1000 Linux Tutorials.