Вопрос

I am looking for some working shell code for auto restart mysql servers if it is not working. here are some code witch i foound in google search, listen 3306 port, if it is not working, restart. if can not restart, reboot the server.

Can this code work? If not, is anyone can share me a working code? If yes, i met syntax error near unexpected tokendone' in bash code`, how to solve it? thanks.

PORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $5}'`
MYSQLIP=`ifconfig eth0|awk '/inet/{print $2}'|cut -c 6-`
while [ `whoami` == "root" ]
do
  if [ "$PORT" == "3306" ];then
    echo "mysql is running......"
  else
    service mysql restart
       if [ "$PORT" == "3306" ];then
       else
           reboot
       fi
  fi
break
done

Modify code:

PORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $5}'`
MYSQLIP=`ifconfig eth0|awk '/inet/{print $2}'|cut -c 6-`
while [ `whoami` == "root" ]
do
  if [ "$PORT" == "3306" ];then
    echo "mysql is running......"
  else
    service mysql restart
       if [ "$PORT" == "3306" ];then
         :
       else
           reboot
       fi
  fi
break
done
Это было полезно?

Решение

Your condition test must execute some sort of code if true.

It looks like you want to reboot if "$PORT" is not "3306".

You should only use break when testing a condition, otherwise the loop will only execute once.

The PORT variable will not update unless you call the code that sets it again after you need it to update.

Also, you don't need to use grep when you are using awk.

#!/bin/bash

callport ()
{
    PORT=`netstat -na|awk -F[:" "]+ '/LISTEN/ && /3306/ {print $5}'`
}
MYSQLIP=`ifconfig eth0|awk '/inet/{print $2}'|cut -c 6-`
while [ `whoami` == "root" ]
do
  callport
  if [ "$PORT" == "3306" ];then
    echo "mysql is running......"
    break
  else
    service mysql restart
    callport
       if [ "$PORT" != "3306" ];then
           reboot
       fi
  fi
done
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top