How to start a Linux service (Bash script) containing an infinite loop in the start method
You should detach the cycle itself to a separated script and run the latter script from the startup one according to the manner preferred in your distribution for a non-self-daemonizing application.
Please notice that your current startup script will likely hang a system boot up even if not run from terminal, at least for most traditional startups (I won't say for systemd and other contemporary ones which could start multiple scripts in parallel, but they definitely will think startup isn't finished). But you could miss it if e.g. logged in via ssh because sshd will start before your script.
In my opinion, it's worth scheduling such kind of script with cron
scheduler rather than writing standalone init script.
cat > /usr/local/bin/watch-mysql.sh <<-"__SEOF__" #!/bin/sh set -e # if this file exists monitoring is stopped if [ -f /var/run/dont-watch-mysql.lck ]; then exit 0 fi process_name="mysqld" restart_process_command="service mysql restart" PGREP="/usr/bin/pgrep" $PGREP ${process_name} if [ $? -ne 0 ] # if <process> not running then # restart <process> $restart_process_command fi__SEOF__# make the script executablechmod u+x /usr/local/bin/watch-mysql.sh# schedule the script to run every 10 minutes(crontab -l ; echo "*/10 * * * * /usr/local/bin/watch-mysql.sh") | uniq - | crontab -
If you simply create the file /var/run/watch-mysql.lck
it won't be monitored.