Lsrei
Lsrei

Reputation: 13

My very basic command is failing on cron but runs fine otherwise, in bash

I'm trying this very basic thing, to output a random number:

NUMBER=$[ ( $RANDOM % 500 )  + 1 ]; echo $NUMBER > /tmp/out

It runs fine directly on the CLI in Debian, but when I try to cron this, either as is:

* * * * * NUMBER=$[ ( $RANDOM % 500 )  + 1 ]; echo $NUMBER > /tmp/out

Or in part of a script in various ways, it consistently fails in my email alerts as:

/bin/sh: Syntax error: "(" unexpected

I'm very out of practice so I expect it's something glaring obvious. I've tried every bracketing type combo I can think of with no luck. What am I missing?

The full mail alerts I received were:

From: Cron Daemon 
Sent: Friday, February 01, 2013 2:41 PM
Subject: Cron <root@host> NUMBER=$[ ( $RANDOM (failed)

/bin/sh: Syntax error: "(" unexpected

Upvotes: 0

Views: 155

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263637

In addition to escaping the % sign, as F. Hauri points out, cron runs commands using /bin/sh, which doesn't necessarily support all the features that bash does.

* * * * * bash -c 'NUMBER=$[ ( $RANDOM \% 500 )  + 1 ]; echo $NUMBER > /tmp/out'

Or better yet, put the command into a script with #!/bin/bash and execute the script from your crontab.

Upvotes: 1

Related Questions