basename Command
Purpose
Returns the base file name of a string parameter.
Syntax
basename String [ Suffix ]
Description
The basename command reads the String parameter, deletes any prefix that ends with a / (slash) and any specified Suffix parameter, and writes the remaining base file name to standard output. The basename command applies the following rules in creating the base file name:
- 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.
- Remove any trailing / characters from the specified string.
- If there are any / characters remaining in the String parameter, remove the prefix of the string up to and including the last / character.
- If a Suffix parameter
is specified and is identical to the characters remaining in the string,
the string is not modified. For example, entering:
results in: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:cns.boo
results in:K > basename /u/dee/desktop/cns.boo .boo
Failure to find the specified suffix within a string is not considered an error.cns
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.
Exit Status
This command returns the following exit values:
Item | Description |
---|---|
0 | Successful completion. |
>0 | An error occurred. |
Examples
- To display the base name
of a shell variable, enter:
The command displays the base name of the value assigned to the shell variable WORKFILE. If the value of the WORKFILE variable is the /home/jim/program.c file, then the command displays program.c.basename $WORKFILE
- To construct a file name
that is the same as another file name, except for its suffix, enter:
This command assigns to the OFILE file the value of the first positional parameter ($1), but with its .c suffix changed to .o. If $1 is the /home/jim/program.c file, OFILE becomes program.o. Because program.o is only a base file name, it identifies a file in the current directory.OFILE=`basename $1 .c`.o
Note: The ` (grave accent) specifies command substitution.
Files
Item | Description |
---|---|
/usr/bin/basename | Contains the basename command. |