分享一个shell脚本的坑:grep匹配+wc取值 在脚本执行后的结果与手动执行结果不一致
2018-10-03 11:59
686 查看
打算在跳板机上写一个shell脚本,批量检查远程服务器上的main进程是否在健康运行中。
先找出其中一台远程机器,查看main进程运行情况
[root@two002 tmp]# ps -ef|grep main root 23448 23422 0 11:40 pts/0 00:00:00 grep --color=auto main [root@two002 tmp]# ps -ef|grep main|grep -v grep|wc -l 0
shell检查脚本如下
[root@two002 tmp]# cat /tmp/main_check.sh #!/bin/bash NUM=$(ps -ef|grep main|grep -v grep|wc -l) if [ $NUM -eq 0 ];then echo "It's not good! main is stoped!" else echo "Don't worry! main is running!" fi
执行脚本
[root@two002 tmp]# sh -x /tmp/main_check.sh ++ grep main ++ grep -v grep ++ wc -l ++ ps -ef + NUM=2 + '[' 2 -eq 0 ']' + echo 'Don'\''t worry! main is running!' Don't worry! main is running! [root@two002 tmp]# sh /tmp/main_check.sh Don't worry! main is running!
如上执行结果,发现脚本执行过程中,看到赋予NUM参数的结果值是2!但是手动执行ps -ef|grep main|grep -v grep|wc -l的结果明明是0!!
这是由于grep匹配的问题,需要grep进行精准匹配,即"grep -w"。这就需要将main_check.sh脚本内容修改如下:
[root@two002 tmp]# cat /tmp/main_check.sh #!/bin/bash NUM=$(ps -ef|grep -w main|grep -v grep|wc -l) if [ $NUM -eq 0 ];then echo "Oh!My God! It's broken! main is stoped!" else echo "Don't worry! main is running!" fi
再次执行检查脚本,就OK了
[root@two002 tmp]# sh -x /tmp/main_check.sh ++ grep -w main ++ grep -v grep ++ wc -l ++ ps -ef + NUM=0 + '[' 0 -eq 0 ']' + echo 'Oh!My God! It'\''s broken! main is stoped!' Oh!My God! It's broken! main is stoped! [root@two002 tmp]# sh /tmp/main_check.sh Oh!My God! It's broken! main is stoped!
故在跳板机上,批量检查远程服务器的main进程运行状态的脚本为:
[root@tiaoban ~]# cat /usr/bin/main_check #!/bin/bash NUM=$(ps -ef|grep -w main|grep -v grep|wc -l) if [ $NUM -eq 0 ];then echo "Oh!My God! It's broken! main is stoped!" else echo "Don't worry! main is running!" fi [root@tiaoban ~]# cat /opt/script/main_check.sh #!/bin/bash for i in $(cat /opt/ip.list) do /usr/bin/rsync -e "ssh -p22" -avpgolr /usr/bin/main_check $i:/usr/bin/ > /dev/null 2>&1 ssh -p22 root@$i "echo $i;sh /usr/bin/main_check" done
相关文章推荐
- Linux下shell脚本手动执行和放在crontab中自动执行的结果不一样
- crontab定时执行脚本与手动执行脚本结果不一致
- crontab执行脚本与手动执行结果不一致
- 分享一个遍历当前文件夹下所以子目录,并在子目录中执行其他操作的shell脚本
- shell 脚本中,grep无法读取前一个命令结果输出的一个原因
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- shell脚本一个分享,直接粘贴过来
- shell命令 grep不以某字符开头、ssh远程执行命令返回结果、ssh远程执行多个命令输入文件
- 从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
- 如何在shell脚本中,判断一个基本命令执行是否成功?
- 从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
- 一个用shell写的执行java程序的脚本
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 定时任务与手动执行脚本时的一个重要注意事项
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 给朋友写了一个从脚本文件逐行加载执行SQL语句的程序,现在分享给将来需要的朋友们参考
- linux0.11是如何加载并执行一个二进制可执行文件和shell脚本文件的?
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- java执行shell命令或者脚本,返回结果到程序
- 脚本中判断Shell命令执行结果