我有一个shell scipt,并在某些时候我想检查如果mysql正在运行,并启动它,如果不是。 我正在尝试以下,但没有任何运气:
set mysqlstatus = `sudo /opt/local/bin/mysqladmin5 ping` if ["$mysqlstatus" != 'mysqld is alive'] then sudo /opt/local/share/mysql5/mysql/mysql.server start fi
脚本run-one是你的朋友:
sudo run-one /opt/local/share/mysql5/mysql/mysql.server start
有关run-one脚本的更多信息:
http://blog.dustinkirkland.com/2011/02/introducing-run-one-and-run-this-one.html
如果因为某种原因无法安装run-one ,
然后将以下代码复制到名为run-one的新文件中:
#!/bin/sh -e # # run-one - run just one instance at a time of some command and # unique set of arguments (useful for cronjobs, eg) # # run-this-one - kill any identical command/args processes # before running this one # # Copyright (C) 2010 Dustin Kirkland <[email protected]> # # Authors: # Dustin Kirkland <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. PROG="run-one" # Cache hashes here, to keep one user from DoS'ing another DIR="$HOME/.cache/$PROG" mkdir -p "$DIR" # Calculate the hash of the command and arguments CMDHASH=$(echo "$@" | md5sum | awk '{print $1}') FLAG="$DIR/$CMDHASH" # Handle run-this-one invocation, by killing matching process first case "$(basename $0)" in run-this-one) ps="$@" # Loop through matching pids for p in $(pgrep -u "$USER" -f "^$ps$" || true); do # Try to kill pid kill $p # And then block until killed while ps $p >/dev/null 2>&1; do kill $p sleep 1 done done # NOTE: Would love to use lsof, but it seems that flock()'s # are not persistent enough, sometimes; use pgrep/pkill now. # pid=$(lsof "$FLAG" | grep "^flock" | awk '{print $2}') || true # [ -z "$pid" ] || kill $pid ;; esac # Run the specified commands, assuming we can flock this command string's hash flock -xn "$FLAG" "$@"
给予执行权限:
chmod +x run-one
最后,使用./run-one或者正确设置你的PATH环境variables来使用它,而不用指定目录。
你也可以看看名为“monit”的软件。 语法和用法是相当普遍和简单的。
杀死mysqld进程并不是一个好主意,因为这会导致数据丢失或损坏的数据库。 优雅的方式是使用“mysqladmin关机”。