2

I created a cronjob in the following way to run a script. The script started a service only if it was down.

Here is the script,

#!/bin/bash
service=influxdb

if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then
echo "$service is running!!!"
else
service $service start
fi

I created a cron job like this,

alphauser@AlphaServer:~$ sudo crontab -e

And then added this line

* * * * * bash /home/alphauser/influx-start.sh > /home/alphauser/output-influx-start.txt

I stored the output in a file just to check its output.

The service stopped and now it was the time for cron to show its magic. But it failed to start the service. I saw the output file and this was written in that,

Starting influxdb...
influxdb process was unable to start [ FAILED ]

then I removed this cronjob from by sudo crontab -r.

I added this line at the end of etc/crontab file i.e,

* * * * * root bash /home/alphauser/influx-start.sh > /home/alphauser/outputinflux.txt

and it worked. The service started and This was the output,

influxdb is running!!!

I want to know that why it failed with sudo crontab -e but it worked with etc/crontab file.

The authentication of sudo cannot be the issue because I added it in the sudo crontab and by chance if that would have been the case, it would have said You must be root to run this script.

luv.preet
  • 5,997

1 Answers1

5

As @steeldriver noticed: the service command fails because it is not in the crontab path. Even as root, crontab jobs run in an environment that is fairly restricted in terms of environmental variables. You need to include the full path of many executables in a command that is to be executed by cron.

In this case, therefore,

/usr/sbin/service $service start

would have worked. How do we know what the exact path of an executable is? Do which service and it will answer /usr/sbin/service.

However, the service command is on its way out and being replaced by its systemd equivalent systemctl. You would do systemctl start $service in a terminal command. Even without sudo, systemctl will figure out that it is not running as root, and ask for your sudo password.

In a crontab, you would use the full path to systemctl utility, which is /bin/systemctl.

So, if you use

/bin/systemctl start $service

it should work.

Jos
  • 30,529
  • 8
  • 89
  • 96