Search code examples
bashshellcronscripting

Use "crontab -l" in if statement to send mail if no crontab for {user}


I am writing a scrip to send a email alert if no crontab is present for the user.

if [[ $(crontab -l) == "no crontab for {user}" ]]; then
    mailx ....
fi

But the script is ending at crontab -l, the body of the if statement is not being executed.

I tried to run grep on the output:

crontab -l | grep "no crontab for {user}"

did not work


Solution

  • I suggest to use crontab's exit code:

    if ! crontab -l 2>/dev/null 1>&2; then
      echo "no crontab";
    else
      echo "crontab";
    fi