Bash script to re-launch program in case of failur

2019-08-12 04:29发布

In linux (I use a Ubuntu), I run a (ruby) program that continually runs all day long. My job is to monitor to see if the program fails and if so, re-launch the program. This consists up simply hitting 'Up' for last command and 'Enter'. Simple enough.

There has to be a way to write a bash script to monitor my program if its stops working and to re-launch it automatically.

How would I go about doing this?

A bonus is to be able to save the output of the program when it errors.

2条回答
Melony?
2楼-- · 2019-08-12 04:55

What you could do:

#!/bin/bash
LOGFILE="some_file.log"
LAUNCH="your_program"

while :
do
    echo "New launch at `date`" >> "${LOGFILE}"
    ${LAUNCH} >> "${LOGFILE}" 2>&1 &
    wait
done

Another way is to periodicaly check the PID:

#!/bin/bash
LOGFILE="some_file.log"
LAUNCH="your_program"

PID=""
CHECK=""

while :
do
    if [ -n "${PID}" ]; then
        CHECK=`ps -o pid:1= -p "${PID}"`
    fi

    # If PID does not exist anymore, launch again
    if [ -z "${CHECK}" ]; then
        echo "New launch at `date`" >> "${LOGFILE}"

        # Launch command and keep track of the PID
        ${LAUNCH} >> "${LOGFILE}" 2>&1 &
        PID=$!
    fi

    sleep 2
done
查看更多
【Aperson】
3楼-- · 2019-08-12 04:59

Infinite loop:

while true; do
  your_program >> /path/to/error.log 2>&1 
done
查看更多
登录 后发表回答