我有一个 shell 脚本,有时我想检查 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
答案1
脚本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
环境变量,以便在不提供目录的情况下使用它。
答案2
您还可以研究名为“monit”的软件。语法和用法非常常见且简单。
答案3
终止 mysqld 进程不是一个好主意,因为这可能会导致数据丢失或数据库损坏。优雅的方式是使用“mysqladmin shutdown”。