How do I write a watchdog daemon in bash?
Based on clarifications in comments, what you actually want is a daemon process that keeps a child running, relaunching it whenever it exits. You want a way to type "./myscript.sh" in an ssh session and have the daemon started.
#!/usr/bin/env bashPIDFILE=~/.mydaemon.pidif [ x"$1" = x-daemon ]; then if test -f "$PIDFILE"; then exit; fi echo $$ > "$PIDFILE" trap "rm '$PIDFILE'" EXIT SIGTERM while true; do #launch your app here /usr/bin/server-or-whatever & wait # needed for trap to work doneelif [ x"$1" = x-stop ]; then kill `cat "$PIDFILE"`else nohup "$0" -daemonfi
Run the script: it will launch the daemon process for you with nohup. The daemon process is a loop that watches for the child to exit, and relaunches it when it does.
To control the daemon, there's a -stop
argument the script can take that will kill the daemon. Look at examples in your system's init scripts for more complete examples with better error checking.