if 语句在 cron 中不起作用

if statement not working in cron

我有以下代码:(record.sh)

cd $(dirname [=10=])

dt=$(date '+%d/%m/%Y %H:%M:%S');
echo $dt;
read action < /home/nfs/sauger/web/pi/action.txt
echo $action;
if [[ $action == *"start"* ]]
then
  echo "start recording"
  ./gone.sh
  exit 1
elif [[ $action == *"stop"* ]]
then
 echo "stop recording"
  ./gone.sh
  exit 1
else 
#More stuff done here
fi

当我手动 运行 这个脚本时,输出如下:

19/01/2016 19:07:11
start
start recording

如果通过(根)cronjob 运行 相同的脚本,则输出如下:

19/01/2016 19:07:01
start

如您所见,文件 "action.txt" 已被毫无问题地读取("start" 两次都被记录)因此这不应该是权限或路径错误的问题。但是当 运行 作为 cronjob 时,不会调用 if 语句。没有 "start recording" 出现。

所以我的问题是:为什么 if 语句在我手动调用脚本时有效,但在通过 cron 完成时却无效?

您的脚本是为 bash 编写的;这些错误几乎肯定表明它是 运行 而不是 /bin/sh

要么添加一个适当的 shebang 并确保以尊重它的方式调用它(/path/to/script 而不是 sh /path/to/script),要么修复它以使其兼容。例如:

case $action in
  *start*)
    echo "start recording"
    ./gone.sh
    exit 1
    ;;
  *stop*)
    echo "stop recording"
    ./gone.sh
    exit 1
    ;;
esac