1

I am trying to run a job on the first weekday of each month with the following crontab entries:

00 07 1-3 * * [ "$(date '+\%a')" == "Mon" ] && echo "Its Monday!"
00 07 1 * * [ "$(date '+\%a')" == "Tue" ] && echo "Its Tuesday!"
00 07 1 * * [ "$(date '+\%a')" == "Wed" ] && echo "Its Wednesday!"
00 07 1 * * [ "$(date '+\%a')" == "Thu" ] && echo "Its Thursday!"
00 07 1 * * [ "$(date '+\%a')" == "Fri" ] && echo "Its Friday!"

But this morning I got the following error:

/bin/sh: 1: [: Thu: unexpected operator
RikT
  • 11

3 Answers3

0

I was looking for a way to do this in a java quartz CronTrigger and ended up on this page. Not sure if this works with regular cron, but quartz supports the notation 0 7 1 1W * ? for first weekday of the month. I'm writing it down here for future me.

0 7 1 1W * ?:

  • Seconds 0
  • Minutes 7
  • Hours 1
  • Day-of-month 1W weekday nearest the first of the month
  • Month *
  • Day-of-Week ? no specific value

Also see the javadoc of org.quartz.CronExpression.

0

From man test:

   STRING1 = STRING2
          the strings are equal

Note that it is =, not ==. However, this is not the only problem...

firas@itsuki ~ % sh
$ [ "$(date '+\%a')" == "Thu" ] && echo "Its Thursday!"
sh: 1: [: \Thu: unexpected operator
$ [ "$(date '+\%a')" = "Thu" ] && echo "Its Thursday!"
$

The other problem is that since your date string +\%a is between single quotes, it will be interpreted literally, and so

$ date '+\%a'
\Thu

which is not what you want. Instead you should remove the unnecessary backslash, and then

$ [ "$(date '+%a')" = "Thu" ] && echo "Its Thursday!"
Its Thursday!
fkraiem
  • 12,555
  • 4
  • 35
  • 40
  • Actually, the \%a is probably to protect % from cron, where % indicates that what follows is to be the input for the command. http://askubuntu.com/a/106440/158442 – muru Dec 01 '16 at 10:15
-1

The problem is a mix of syntax and suitable commands in the code you're using, rather than the way the cron has been set up. For what you're trying to achieve, the bash code should really utilise an if statement, like this:

if [[ "$(date '+\%a')" == "\Thu" ]]; then echo "Its Thursday!"; fi

(Note the extra set of square brackets, use of semi-colon, and the terminating fi entry).

The result of which looks like this:

chris@loki:/$ if [[ "$(date '+\%a')" == "\Thu" ]]; then echo "Its Thursday!"; fi
Its Thursday!

It's worth noting that in your code, the boolean && isn't suitable, as it's really supposed to be used for stringing conditional statements. For example:

if [ $condition1 ] && [ $condition2 ]

Hope this is what you were after!

  • This is actually wrong. Shell uses shortcut evaluation, so && is just fine in place of if. It's questionable however which of the two equivalent versions is more readable. – user10489 May 27 '21 at 12:08