在cron作业中使用'which'命令

我有一台cron作业,每天在Linux服务器上运行一次,并在其中执行的脚本中进行testing:

# Validate ffmpeg is installed if [ $(which ffmpeg | grep -c "ffmpeg") -eq 0 ]; then echo "error: ffmpeg is not installed!" | tee -a "$log" exit 1 fi 

每天当我检查日志文件时, ffmpeg is not installed!消息ffmpeg is not installed! 在日志中,结果工作没有被执行。 如果我运行在shell中的whichtesting一切正常,当我执行脚本一切正常。

是否有一些固有的防止它能够正确使用which命令?

在你的crontab文件的顶部放置SHELL和PATH声明:

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

看到这个SE post了解更多细节。

cron默认的SHELL和PATH是SHELL=/bin/shPATH=/usr/bin:/bin (从man 5 crontab手册页)。

从cron运行起,它可能不会启动你的path。 有几种方法可以让我知道最容易find的path是硬编码的path。

做一个:

 locate which 

我的回报如下:

 [user@server ~]$ locate which |grep bin /usr/bin/which 

然后改变你的脚本来做:

 if [ $(/usr/bin/which ffmpeg | grep -c "ffmpeg") -eq 0 ]; then echo "error: ffmpeg is not installed!" | tee -a "$log" exit 1 fi 

另一个选项是在crontab中设置环境和path:

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