Bash - 在 if 语句中从 crontab -l 读取

Bash - Read from crontab -l in an if statement

我正在尝试读取 crontab -l 的输出以验证是否正确添加了 cronjob。

现在 crontab -l 的输出是:

0 */3 * * * ~/scripts/snapshot.sh(这是应该的)。

我要检查的脚本如下:

#!/bin/bash

if `crontab -l` = "0 */3 * * * ~/scripts/snapshot.sh"; then
       echo "Done creating a cronjob"
else
       echo "NOTICE: Failed creating a crontab"
fi

我尝试了多种方法并且 none 成功了,如果我执行以下操作:

#!/bin/bash
croncheck=`crontab -l`

echo $croncheck

#or
#echo `crontab -l`

输出显示如下:

0 */3 cronjobs scripts test.sh cronjobs scripts test.sh cronjobs scripts test.sh ~/scripts/snapshot.sh

而不是 what it should show(应该是什么)。

我会使用正则表达式进行搜索,但如果正则表达式中仍然有一些魔力,请稍微测试一下。这也可以扩展为匹配任何有效时间,而不仅仅是您提供的时间。

if [ -z "`crontab -l | grep '^0 \*/3 \* \* \* ~/scripts/snapshot.sh' `" ]; then
  echo "not found, something is wrong"
else
  echo "found, this is ok"
fi