在crontab中运行脚本 - 找不到命令:

时间:2017-06-24 00:32:32

标签: linux bash path cron reboot

我在root crontab中设置了一个脚本,该脚本应该使用reboot命令重启我的机器。

但是,尽管reboot: command not found位于root用户的路径中,但我得到reboot

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

我的剧本:

#!/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用户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

...是的,这只是一个临时的解决方法,而我弄清楚为什么互联网不断下降。

1 个答案:

答案 0 :(得分:4)

cron jobs在非常基本的环境设置下运行;除此之外,默认PATH只是/usr/bin:/bin使用用户的常规shell设置。有几种方法可以解决这个问题:

  • 使用脚本中的完整路径(即/sbin/reboot)。
  • 在使用reboot(即PATH=/usr/bin:/bin:/usr/sbin:/sbin)之前在脚本中设置PATH。
  • 在脚本条目之前在crontab中设置PATH(语法与脚本中的相同)。
相关问题