首页 > 系统服务 > 详细

Linux shell 字符串常用操作

时间:2015-08-26 20:33:43      阅读:303      评论:0      收藏:0      [点我收藏+]
  1. 取变量的长度

[root@oldjun-study scripts]# var=oldboy123
[root@oldjun-study scripts]# echo ${var}
oldboy123
[root@oldjun-study scripts]# echo ${#var}
9

#例如:
#以下判断用read输入一个值,如果长度为0,则值为空,否则打印出变量的值
[root@oldjun-study scripts]# cat if4.sh 
#!/bin/bash
read -p "pls input a num: " a

if [ ${#a} -eq 0 ]
then 
    echo "a is null,pls input a nums again!"
    exit 1
else
    echo "a=$a"
fi

#测试
[root@oldjun-study scripts]# sh if4.sh 
pls input a num: 
a is null,pls input a nums again!
[root@oldjun-study scripts]# sh if4.sh 
pls input a num: d
a=d
[root@oldjun-study scripts]# sh if4.sh 
pls input a num: 123
a=123



2. 文件名和目录的截取

[root@oldjun-study scripts]# test="/etc/sysconfig/network-scripts/ifcfg-eth0"
[root@oldjun-study scripts]# echo ${test}
/etc/sysconfig/network-scripts/ifcfg-eth0

#取文件名
[root@oldjun-study scripts]# echo ${test##*/}
ifcfg-eth0

#取目录
[root@oldjun-study scripts]# echo ${test%/*} 
/etc/sysconfig/network-scripts

#使用命令basename 和dirname也可以达到同样的效果
[root@oldjun-study scripts]# echo `basename $test`
ifcfg-eth0
[root@oldjun-study scripts]# echo `dir $test`     
/etc/sysconfig/network-scripts/ifcfg-eth0


Linux shell 字符串常用操作

原文:http://l19891223j.blog.51cto.com/888280/1688392

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!