码迷,mamicode.com
首页 > 系统相关 > 详细

shell 中 basename 的简单使用

时间:2017-03-07 14:24:57      阅读:413      评论:0      收藏:0      [点我收藏+]

标签:shell basename

   

  在shell 脚本中$0 通常用于显示脚本的名称,在不使用basename 的时候会显示脚本的路径名称


 例如

 cat test5.sh 
#!/bin/bash 
# testing the $0 parameter 

echo the zero parameter is set to:$0

 执行脚本

bash /root/shell/test5.sh 

the zero parameter is set to:/root/shell/test5.sh ##显示了脚本的路径


添加basename 后 

#!/bin/bash 
# testing the $0 parameter 
name=$(basename $0 )
echo the zero parameter is set to:$name


执行脚本 

 bash /root/shell/test5b.sh 

the zero parameter is set to:test5b.sh  ##直接显示脚本名称


简单实例,根据脚本的不同名称执行不同的功能,当脚本名称是addem,执行加法、是multem的时候执行乘法


脚本如下

#!/bin/bash
#Testing a multi-function script 
name=$(basename $0)
#

if [ $name = "addem" ]
then 
  total=$[ $1 + $2 ]
elif [ $name = "multem" ]
then 
  total=$[ $1 * $2 ]
fi
echo The calculated value is $total



cp test6.sh addem 

cp test6.sh multem


执行addem 脚本


./addem 25 3

The calculated value is 28


执行multem 脚本


[root@VM_71_179_centos shell]# ./multem 3 5

The calculated value is 15


本文出自 “sdsca” 博客,请务必保留此出处http://sdsca.blog.51cto.com/10852974/1903822

shell 中 basename 的简单使用

标签:shell basename

原文地址:http://sdsca.blog.51cto.com/10852974/1903822

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!