首先使用 --help 参数查看一下。
basename命令参数很少,很容易掌握。
- $ basename --help
用法示例:
$ basename /usr/bin/sort 输出"sort"。$ basename ./include/stdio.h .h 输出"stdio"。为basename指定一个路径,basename命令会删掉所有的前缀包括最后一个slash(‘/’)字符,然后将字符串显示出来。
basename命令格式:
basename [pathname] [suffix]basename [string] [suffix]suffix为后缀,如果suffix被指定了,basename会将pathname或string中的suffix去掉。
示例:
- $ basename /tmp/test/file.txt
- file.txt
- $ basename /tmp/test/file.txt.txt
- file
注意点:
1、如果像下面脚本中传递参数给basename,参数为空,basename会将参数左移2、basename最多接受两个参数,如果设置的参数多于两个,会提示错误。
以下是一个简单的脚本,测试了一下basename:
- #!/bin/bash
- # basename.sh
- echo Testing basename
- echo -------------
- echo "basename \$1/\$2 .txt; suffix is .txt"
- filename=`basename $1/$2.txt`
- echo $filename
- echo -------------
- echo "basename ab.c .c; suffix is .c"
- basename ab.c .c
- echo "basename ab b; suffix is b"
- basename ab b
- echo -------------
- echo Testing \$\@ and \$\#
- echo Output \$\@
- echo $@
- echo Output \$\#
- echo $#
- # end of basename.sh
脚本运行结果:
- 没有参数传递的情况:
- $./basename.sh
- Testing basename
- -------------
- basename $1/$2.txt; suffix is.txt
- /
- -------------
- basename ab.c .c; suffix is .c
- ab
- basename ab b; suffix is b
- a
- Testing $@ and $#
- -------------
- Output $@
- Output $#
- 0
- 传递参数的情况:
- $ ./basename.sh 1.txt
Testing basename
---------
basename $1/$2 .txt;suffix is .txt
1
--------
basename ab.c .c;suffix is .c
ab
basename ab b;suffix is b
a
---------
Testing $@ and $#
Output $@
1.txt
Output $#
1
=============================================================
./basename.sh 1.txt 2.txt
Testing basename
---------
basename $1/$2 .txt;suffix is .txt
2
--------
basename ab.c .c;suffix is .c
ab
basename ab b;suffix is b
a
---------
Testing $@ and $#
Output $@
1.txt 2.txt
Output $#
2
额外补充:
1、$@$@ 为传递的参数2、$#$# 为传递参数的数量
就像脚本执行后的结果:
- Testing $@ and $#
- -------------
- Output $@
- 1.txt 2.txt
- Output $#
- 2
3、$?
是shell变量,表示"最后一次执行命令"的退出状态,一般0表示成功,非0数值表示没有成功。切记:$?永远表示shell命令最后一次执行后的退出状态,当函数执行完毕后,如果又执行了其它命令,则 $?不再表示函数执行后的状态,而表示其它命令的退出状态.4、$!代表pid,进程id5、$$代表ppid,父进程id
- $ ./skype&
- [2] 13549
- $ echo $!
- 13549
- $ echo $$
- 13032
- $ ps -ef | grep skype
- luck 13549 13032 4 19:19 pts/0 00:00:00 skypeTesting basename