变量替换总结:
1、${变量#匹配规则} #从头开始匹配,最短删除
2、${变量##匹配规则} #从头开始匹配,最长删除
3、${变量%匹配规则} #从尾开始匹配,最短删除
4、${变量%%匹配规则} #从尾开始匹配,最长删除
5、${变量/旧字符串/新字符串} #替换变量内旧的字符串为新字符串,自替换第一个
6、${变量//旧字符串/新字符串} #替换变量内旧的字符串为新字符串,全部替换
例子1:
var1="I love you,Do you love me"
[root@k8smaster shell]# var2=${var1#*ov}
[root@k8smaster shell]# echo $var2
e you,Do you love me
[root@k8smaster shell]# var2=${var1##*ov}
[root@k8smaster shell]# echo $var2
e me
[root@k8smaster shell]# var3=${var1%ov*}
[root@k8smaster shell]# echo $var3
I love you,Do you l
[root@k8smaster shell]# var3=${var1%%ov*}
[root@k8smaster shell]# echo $var3
I l
[root@k8smaster shell]# var4=${PATH/bin/BIN}
[root@k8smaster shell]# echo $var4
/usr/local/sBIN:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
[root@k8smaster shell]# var5=${PATH//bin/BIN}
[root@k8smaster shell]# echo $var5
/usr/local/sBIN:/usr/local/BIN:/usr/sBIN:/usr/BIN:/root/BIN
需求描述:
写一个Nginx监控脚本,如果Nginx宕掉,则该脚本可以检测到并将进程启动。
#!/bin/sh
while true
do
this_pid=$$
ps -ef|grep nginx|grep -v nginx|grep -v $this_pid &> /dev/null
if [ $? -eq 0 ];then
echo "Nginx is running well"
sleep 3
else
systemctl start nginx
sleep 3
echo "Nginx is down,Start it ......"
fi