Example Bash Script which Monitors if a Program has Died, and Restarts it

Background

Here’s a quick script that might prove useful if you need to watch if a program is running and restart it if it stops for whatever reason. It is by no means fault tolerant, but could be adapted to be more so if needed.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
 
# NAME: check_dropbox.bash
# DESC: watch if dropbox is running
 
check_process() {
  echo "$ts: checking $1"
  [ "$1" = "" ]  && return 0
  [ `pgrep -n $1` ] && return 1 || return 0
}
 
while [ 1 ]; do
  # timestamp
  ts=`date +%T`
 
  echo "$ts: begin checking..."
  check_process "dropbox"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
  sleep 5
done

Running this script, the output would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# SHELL #2
% dropbox start -i
Starting Dropbox...Done!
 
# SHELL #1
% check_dropbox.bash
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
 
# SHELL #2
% dropbox stop
Dropbox daemon stopped.
 
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: hot running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox

Things to consider with this script, in its current form, it’s way to chatty, so getting rid of the echo statements would be the first things to change. 2nd would probably be the frequency, every 5 secs. is too aggressive. Again it’s just meant as an example of how to get something basic like this going. HTH.

This entry was posted in bash, monitoring, script, Syndicated, tip, tutorials. Bookmark the permalink.

Comments are closed.