0

I have new to scripts .. I want to monitor service on the server - we have two scripts 1 - for checking service is running or not (checking.sh) 2 - start the service (start.sh)

I would like to merge two scripts into single (monitor.sh) and schedule/ cron it. how do I run second script based on first script result IF first script result is 0 need to start the service (second script need to run) ,if first script result is 1 second script no need to run and exit main script.

1 Answer 1

1

This is what exit codes are for. So, for your monitor script, we could do something like:

#!/bin/bash
# monitor.sh  -- checks if a Thing is doing its Thing
if [[ -r /var/run/myjob.pid ]]; then
    if kill -0 $( cat /var/run/myjob.pid ); then
        exit 0   # The process is alive, job is presumably running
    else
        exit 1   # Well, we had a PID file, but it was orphaned.
    fi
else
    exit 2 # no PID file, job presumably not running
fi

We use a different exit code for each state we wish to handle. Then, for our service checker:

#!/bin/bash
# check.sh -- Checks to see if Thing is Thinging and, if not, start it
if ! /path/to/monitor.sh; then
    /path/to/start.sh
fi

And now, the script that runs the job:

#!/bin/bash
# start.sh - do a Thing
if [[ -r /var/run/myjob.pid ]]; then
    echo "A Thing is already being done!" 1>&2
    exit 1 
else
    echo $$ > /var/run/myjob.pid
    trap 'rm /var/run/myjob.pid' EXIT
    do_Thing_related_things
fi

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.