This article is reproduced in: http://monkeymusic.blog.163.com/blog/static/4797639200912533652666/
Purpose
Returns the basic file name of a string parameter.
Syntax
Basename string [suffix]
Description
The basename command reads the string parameter, deletes the prefix ending with a slash (/) and any specified suffix parameter, and writes the remaining basic file names to the standard output. The basename command applies the following rule to create the basic file name:
- If the string parameter is // (double slash) or if the string parameter contains all the slash characters, change the string to a single slash (slash ). Skip steps 2 to 4.
- Removes any trailing/character from the specified string.
- If any character is left in the string parameter, the prefix of the string is removed until (inclusive) The last character.
- If the suffix parameter is specified and it is the same as the remaining characters in the string, this string is not modified. For example, enter:
K > basename /u/dee/desktop/cns.boo cns.boo
The result is:
cns.boo
If the suffix parameter is specified and it is different from all characters in the string, but it is the same as the string suffix, the specified suffix is removed. For example, enter:
K > basename /u/dee/desktop/cns.boo .boo
The result is:
cns
The specified suffix cannot be found in the string and cannot be used as error handling.
The basename and dirname commands are usually used in Shell
Replace the command in the script to specify the name of the output file that is different from the specified input file name.
Exit status
This command returns the following exit value:
0 successfully completed
> 0 Error
Example
- To display the basic name of a shell variable, enter:
basename $WORKFILE
This command displays the specified shell variableWorkfileThe basic name of the value. IfWorkfileThe variable value is in the/home/Jim/program. c file.Program. c.
- To construct a file name with the same name (except the suffix) as another file, enter:
OFILE=`basename $1 .c`.o
This command is specifiedOfileParameters at the first position of the file ($1), But its. CSuffix changed. O. If$1Is the/home/Jim/program. c file, thenOfileBecomeProgram. o. BecauseProgram. oIt is only a basic file name that identifies the file in the current directory.