15-1 shell脚本编程进阶字符串切片和高级变量

发布时间 2023-06-14 11:34:45作者: 最拉的刺客

一、显示字符的长度

[root@centos8 ~]#str=`echo {a..z} |tr -d ' '`
[root@centos8 ~]#echo str
str
[root@centos8 ~]#echo $str
abcdefghijklmnopqrstuvwxyz
[root@centos8 ~]#name=刘进喜
[root@centos8 ~]#echo ${#name}
3
[root@centos8 ~]#echo ${#str}
26

二、切片

root@centos8 ~]#echo ${str:3}
defghijklmnopqrstuvwxyz
[root@centos8 ~]#echo ${str:3:4}
defg
[root@centos8 ~]#echo ${str: -3}    切片倒数第三个
xyz

[root@centos8 ~]#echo ${str:3: -3}  去头去尾
dfghijklmnopqrstuvw

 

三、基于模式取子串

从左到右取

[root@centos8 ~]#url=http://www.baidu.com/index.html
[root@centos8 ~]#echo ${url#*/}
/www.baidu.com/index.html
[root@centos8 ~]#url=http://www.baidu.com:8080/index.html
[root@centos8 ~]#url=httpecho ${url#*:}  懒惰模式
//www.baidu.com:8080/index.html
[root@centos8 ~]#echo ${url##*:}            贪婪模式
8080/index.html
[root@centos8 ~]#
从右到左取

[root@centos8 ~]#echo ${url%:*}
http://www.baidu.com
[root@centos8 ~]#echo ${url%%:*}
http
[root@centos8 ~]#

 

替换

[root@centos8 ~]#getent passwd root
root:x:0:0:root:/root:/bin/bash
[root@centos8 ~]#line=`getent passwd root`
[root@centos8 ~]#echo ${line root liujinxi}
-bash: ${line root liujinxi}: bad substitution
[root@centos8 ~]#echo ${line/root/liujinxi}
liujinxi:x:0:0:root:/root:/bin/bash
[root@centos8 ~]#

四、间接变量引用

[root@centos8 ~]#ceo=name
[root@centos8 ~]#name=liujinxi
[root@centos8 ~]#echo $$ceo
1765ceo
[root@centos8 ~]#echo $$ceo
1765ceo
[root@centos8 ~]#echo '$'$ceo
$name
[root@centos8 ~]#eval echo '$'$ceo
liujinxi
[root@centos8 ~]#

批量创建用户脚本(间接引用变量)

[root@centos8 ~]#cat create_user.sh 
#!/bin/bash
n=$#
[ $n -eq 0  ] && { echo "Usage: `basename $0` username..." ; exit 2 ; }
for i in `eval echo {1..$n}` ;do
        user=${!i}
        id $user &> /dev/null && echo $user id exist || { useradd $user; echo $user created;  }
done