参考
1、shell脚本start、stop、restart_爱学习 爱分享博客-CSDN博客
2、echo 拼接字符串:https://www.csdn.net/tags/OtTacg1sMTc5MS1ibG9n.html
三、字符串判空:
shell判断字符串空的方法-linux运维-PHP中文网
1、学一下while read line
这个命令对于批量关闭某些过程的遍历非常有用
[root@lhy-05 prometheus]# docker ps | awk '{print $1}' CONTAINER 44b52fb4239d 6c167d8bf4e0 5ab159dab98c [root@lhy-05 prometheus]#
找到操作容器并输出容器id
str="-test" docker ps | awk '{print $1}' | while read pid do tmp=${pid}${str} echo ${tmp} done
[root@lhy-05 prometheus]# sh test.sh CONTAINER-test 44b52fb4239d-test 6c167d8bf4e0-test 5ab159dab98c-test [root@lhy-05 prometheus]#
2.学会找出某个过程是否存在
查看Prometheus是否存在启动容器
[root@lhy-05 prometheus]# cat test.sh container_id=`docker ps | grep prometheus | awk '{print $1}'` if [ -n "${container_id}" ];then echo ${container_id} else echo "prometheus进程不存在" fi
3、stop|start|restart
需求:写个shell只允许脚本输入start,stop和restart参数,实现Prometheus docker启动、停止和重启容器的功能
[root@lhy-05 prometheus]# cat run.sh #!/bin/bash start(){ docker start prometheus } stop(){ container_id=`docker ps | grep prometheus | awk '{print $1}'` if [ -z "${container_id}" ];then echo "dockerprometheus is not running" else docker stop ${container_id} fi } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo 'Only param {start|stop|restart} is supported' exit 1 ;; esac