linux basename命令学习

首先使用 --help 参数查看一下。 basename命令参数很少,很容易掌握。
 
  1. $ 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去掉。
示例:
 
  1. $ basename /tmp/test/file.txt
  2. file.txt
  3. $ basename /tmp/test/file.txt.txt
  4. file
 
注意点:
1、如果像下面脚本中传递参数给basename,参数为空,basename会将参数左移
2、basename最多接受两个参数,如果设置的参数多于两个,会提示错误。

 
以下是一个简单的脚本,测试了一下basename:
  1. #!/bin/bash
  2. # basename.sh
  3. echo Testing basename
  4. echo -------------
  5. echo "basename \$1/\$2 .txt; suffix is .txt"
  6. filename=`basename $1/$2.txt`
  7. echo $filename
  8. echo -------------
  9. echo "basename ab.c .c; suffix is .c"
  10. basename ab.c .c
  11. echo "basename ab b; suffix is b"
  12. basename ab b
  13. echo -------------
  14. echo Testing \$\@ and \$\#
  15. echo Output \$\@
  16. echo $@
  17. echo Output \$\#
  18. echo $#
  19. # end of basename.sh
脚本运行结果:
 
  1. 没有参数传递的情况:

  2. $./basename.sh
  3. Testing basename
  4. -------------
  5. basename $1/$2.txt; suffix is.txt
  6. /
  7. -------------
  8. basename ab.c .c; suffix is .c
  9. ab
  10. basename ab b; suffix is b
  11. a
  12. Testing $@ and $#
  13. -------------
  14. Output $@

  15. Output $#
  16. 0

  17. 传递参数的情况:

  18. $ ./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、$#
$# 为传递参数的数量

就像脚本执行后的结果:
 
  1. Testing $@ and $#
  2. -------------
  3. Output $@
  4. 1.txt 2.txt
  5. Output $#
  6. 2
3、$? 
    是shell变量,表示"最后一次执行命令"的退出状态,一般0表示成功,非0数值表示没有成功。
 
切记:
$?永远表示shell命令最后一次执行后的退出状态,当函数执行完毕后,如果又执行了其它命令,则 $?不再表示函数执行后的状态,而表示其它命令的退出状态. 
4、$!
    代表pid,进程id
 
5、$$
    代表ppid,父进程id
 
  1. $ ./skype&
  2. [2] 13549
  3. $ echo $!
  4. 13549
  5. $ echo $$
  6. 13032
  7. $ ps -ef | grep skype
  8. luck 13549 13032 4 19:19 pts/0 00:00:00 skypeTesting basename


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值