4

I've set a script in my root crontab that is supposed to restart my machine with the reboot command.

However, I am getting a reboot: command not found despite the fact that reboot is in the root user's path.

$ sudo su
$ which reboot
/sbin/reboot
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/bin

My script:

#!/bin/bash

ping 8.8.8.8 -c 1 > /dev/null 2>&1; exit_code=$?
time_stamp=$(date +"%Y%m%d-%H%M")

if [ $exit_code -ne 0 ]; then
    (1>&2 echo "$time_stamp: failed with exit code $exit_code; restarting now")
    reboot
else
    echo "$time_stamp: ok"
fi

root user crontab:

$ sudo crontab -l
58 * * * * /home/pi/github/ping-restart/ping-restart.sh >> /home/pi/github/ping-restart/cron.log 2>&1
$ sudo su
58 * * * * /home/pi/github/ping-restart/ping-restart.sh >> /home/pi/github/ping-restart/cron.log 2>&1

...yes, this is only a temporary workaround while I figure out why the internet keeps dropping.

ning
  • 1,823
  • 1
  • 19
  • 25
  • Maybe try using the absolute path `/sbin/reboot`... – l'L'l Jun 24 '17 at 00:47
  • @l'L'l This seems to work. A script with `which reboot` in crontab has no output (indicating not found), while `which /sbin/reboot` has the output `/sbin/reboot`, as expected. Any idea why `reboot` by itself does not work? – ning Jun 24 '17 at 01:05
  • Because `cron` has no clue of where the reboot command is, so you have to give the location. In `cron` only certain commands can be called using just the name, so often you need to give it the absolute path. – l'L'l Jun 24 '17 at 01:41
  • 1
    @l'L'l: I'm not sure I understand. I'm able to use other scripts in the root user crontab that has commands that are called by name instead of their full path (`date` as in `/bin/date`, `basename` as in `/usr/bin/basename`,`traceroute` as in `/usr/sbin/traceroute`). What's so special about `reboot`? – ning Jun 24 '17 at 02:01
  • See Gordon's answer... – l'L'l Jun 24 '17 at 02:02

1 Answers1

7

cron jobs run with a very basic environment setup; among other things, the default PATH is just /usr/bin:/bin. It does not use the user's regular shell setup. There are several ways to solve this:

  • Use the full path in the script (i.e. /sbin/reboot).
  • Set PATH in the script before using reboot (i.e. PATH=/usr/bin:/bin:/usr/sbin:/sbin).
  • Set PATH in the crontab before the entry for your script (syntax is the same as in the script).
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • 1
    This seems 100% to be what's happening. Verified it too, setting `echo $PATH > cron_path_log` as a job. – ning Jun 24 '17 at 02:29