Get the App
SLTechnology News&Howtos  ›  Servers  › 

To share with you a shell script pit.

Shulou Source: shulou.com Published: 2022-06-02 05:14:55 09月15日 Update

I'm going to write a shell script on the springboard machine that will batch check that the main process on the remote server is running healthily.

First find one of the remote machines and see how the main process works

[root@two002 tmp]# ps -ef|grep mainroot 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

The shell check script is as follows

[root@two002 tmp]# cat /tmp/main_check.sh#!/ bin/bashNUM=$(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

execute scripts

[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.shDon't worry! main is running!

As a result of the above execution, it is found that during the script execution process, the result value assigned to the NUM parameter is 2! But manually execute ps -ef| grep main| grep -v grep| Wc -1 is 0!

This is due to the problem of grep matching, which requires grep to match exactly, i.e."grep -w." This requires modifying the main_check.sh script as follows:

[root@two002 tmp]# cat /tmp/main_check.sh#!/ bin/bashNUM=$(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

Run the check script again and it's 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.shOh! My God! It's broken! main is stoped!

Therefore, on the springboard machine, the script for batch checking the running status of the main process of the remote server is:

[root@tiaoban ~]# cat /usr/bin/main_check#!/ bin/bashNUM=$(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>&1ssh -p22 root@$i "echo $i;sh /usr/bin/main_check"done

Tags: Scripts checks results processes runs servers springboards services precision health content again parameters such as above case manual machine status process this is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Huawei MySQL Shulou Technology Redmi