crontab不执行脚本中命令

我的程序部署在树莓派上,为了方便自动更新部署,在树莓派上建立了crontab,每隔几分钟就从git上更新一下自动更新脚本,然后在本地执行。

*/5 * * * * cd /home/pi/code/market_data_fetcher && git fetch && git checkout origin/kotlin auto.sh && ./auto.sh

auto.sh 脚本主要逻辑是判断当前机器是否是指定的机器(因为部署了两台树莓派),然后再判断当前脚本是否已经在运行,防止重复运行。最后执行部署脚本deploy.sh

#!/bin/bash
# host name to be controlled
HOST_NAME=raspberrypi1
#HOST_NAME=raspberrypi2


localhost=$(hostname)
if [ ! "${localhost}" == "${HOST_NAME}" ];then
    exit
fi

runing=$(ps aux | grep "deploy.sh" | grep -v grep)
if [ ! -z "$runing" ];then
    exit
fi

echo "start at -> $(date "+%Y-%m-%d %H:%M:%S")" > .log
#git checkout master
./deploy.sh >> .log
#~/deploy/market_data_fetcherd/bin/market_data_fetcherd restart
echo "end at -> $(date "+%Y-%m-%d %H:%M:%S")" >> .log

在deploy脚本中使用了gradle

gradle clearJar
gradle build -x test
gradle --stop

从日志来看,每次执行都跳过了gradle的执行

start at -> 2019-01-16 08:26:07
Your branch is up-to-date with 'origin/kotlin'.
HEAD is now at f9fe365 test
Already up-to-date.
Stopping market_data_fetcherd... done.
Starting market_data_fetcherd... done.
end at -> 2019-01-16 08:26:12

最终发现是因为我手动安装gradle,将gradle安装在了/opt/gradle目录下,然后通过export path导出了gradle命令

export PATH=$PATH:/opt/gradle/gradle-4.8.1/bin

但是crontab的path中并不包含gradle命令目录,所以crontab找不到gradle命令

pi@raspberrypi1:~/deploy/market_data_fetcherd $ cat /etc/crontab
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

解决办法是将gradle导出到crontab的path中去

ln -s /opt/gradle/gradle-4.8.1/bin/gradle /usr/bin/gradle

其他在crontab中使用的命令也一样,一定要确保使用的命令在crontab的path中!

你可能感兴趣的:(crontab不执行脚本中命令)