1

I'm trying to read the output from crontab -l to verify that the cronjob got added correctly.

Output of crontab -l right now is:

0 */3 * * * ~/scripts/snapshot.sh (which is what it should be).

My script to check is the following:

#!/bin/bash

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

I've tried multiple ways and none worked, if I do the following:

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

echo $croncheck

#or
#echo `crontab -l`

The output shows this:

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

Instead of what it should show (what it should be).

Fadi
  • 1,329
  • 7
  • 22
  • 40
  • 1
    * is expanding to file names – ojblass Aug 17 '15 at 20:46
  • So how would I be able to get it to work? Can you please help? – Fadi Aug 17 '15 at 20:49
  • 1
    and "=" is a bit less then I expect for string compare. You could single-quote the compare string, but I would suggest writing a regexp to check. For bash string compare my first hit was: http://stackoverflow.com/questions/2237080/how-to-compare-strings-in-bash-script – flaschenpost Aug 17 '15 at 20:49
  • 1
    `if [ -z \`crontab -l | grep '^0 \*/3 \* \* \* ~/scripts/snapshot.sh' \` ]; then ... ` since everything in your version breaks if you need another cronjob. – flaschenpost Aug 17 '15 at 20:50
  • flaschenpost, could you put that as an answer so I can mark is as answered? Thank you again! – Fadi Aug 17 '15 at 20:53
  • Enclose the expected output in single quotes (`'`) to avoid the shell expand the asterisks (`*`). – axiac Aug 17 '15 at 21:21

1 Answers1

1

I would search with a regexp, but test it a bit if there is still some magic in the regexp. This could be also extended to match any valid time, not just the one you gave.

if [ -z "`crontab -l | grep '^0 \*/3 \* \* \* ~/scripts/snapshot.sh' `" ]; then
  echo "not found, something is wrong"
else
  echo "found, this is ok"
fi
kenorb
  • 155,785
  • 88
  • 678
  • 743
flaschenpost
  • 2,205
  • 1
  • 14
  • 29
  • By the way, your code works but it gives a small error before it echoes out the answer (only when it says found, this is ok). The error is `[: too many arguments` – Fadi Aug 18 '15 at 15:14
  • 1
    ah, of course, i've missed the double quotes. `"\`crontab -l...\`"` – flaschenpost Aug 18 '15 at 15:34