N
N
Nikolai Shevtsov2015-05-20 16:23:04
bash
Nikolai Shevtsov, 2015-05-20 16:23:04

How to make a bash script run correctly in crontab?

Greetings!
OS FreeBSD 7.3
Bash script manually works out without any problems:

#!/bin/bash
        ret=$(ps aux | grep [s]cript | wc -l)
        if [ "$ret" -eq 0 ]
then {
        echo "Running script"
        sleep 1  #delay
        script.sh start
        exit 1
}
else
{
        echo "EXIT. script already running!"
        exit 1
}
fi;

But he doesn't want to work properly in crontab. No matter how I add it. I threw off the output of the value of the ret variable from it to the log, and in any case it turns out to be equal to zero, although in reality this is not the case. PATH was added to the job by krone.
SHELL=/bin/bash
[email protected]
PATH=/sbin:/bin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/home/admin/bin
* * * * * /usr/local/script.sh

Absolute paths to ps, grep and wc prescribed. Everything is useless. Where to dig?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
Nikolay Shevtsov, 2015-05-21
@coliator

Thank you all for your advice, it's just a pity they didn't help.
I did not succeed in finding out why the "-eq" operator worked incorrectly. Therefore, the comparison began to be done in a different way, and everything from under cron worked correctly.

#!/bin/bash
if [ -z "$(pgrep -f [s]cript)" ]
then {
        echo $(date +%Y-%m-%d:%k:%M:%S) "Running script" >> /var/log/script_log
        sleep 1  #delay
        /usr/local/script.sh start
        exit 1
} else {
        echo $(date +%Y-%m-%d:%k:%M:%S) "EXIT. script already running!" >> /var/log/script_log
        exit 1
}
fi

D
Denis Verbin, 2015-05-20
@rez0n

In my opinion, you have a problem in the path to the script.sh file

A
athacker, 2015-05-21
@athacker

At a minimum, /usr/bin is missing from your PATH. Meanwhile:
% whereis grep
grep: /usr/bin/grep /usr/share/man/en.UTF-8/man1/grep.1.gz /usr/src/usr.bin/grep

E
Eddy_Em, 2015-05-20
@Eddy_Em

To prevent crond from killing the script, you need to "tear off" this script: for example, run it through nohup and in the background.
In general, it is better to run it from inittab, marking it as respawn, so that init will restart the script in case it falls off. If a restart is not needed, you can generally do it humanly: write a simple init wrapper and shove it where your scripts for the current runlevel are.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question