# Have a script execute a command randomly every now and then

I have a script which I am scheduling to run daily with Cron. However I want a certain section of the script to only run randomly occasionally, with a certain probability of executing on any given day.

Here's my basic idea.

use \$RANDOM and cut to get a single random digit:

``````echo \$RANDOM | cut -c1
``````

use an if/then test to evaluate this digit and execute only when it matches a certain value:

``````if [(echo \$RANDOM | cut -c1) = 3]; then
echo "YES" >> ~/result.txt
fi
``````

However, this is not working. The script fails with the following:

``````./testscript: line 3: syntax error near unexpected token `echo'
./testscript: line 3: `if [(echo \$RANDOM | cut -c1) = 3]; then'
``````

I think the idea is sound, but I'm guessing I'm getting the syntax wrong.

Any ideas?

Using bash on Mac OSX 10.7.2

Possibly interesting sidenote: I ran `echo \$RANDOM | cut -c1` 100,000 times and then worked out the frequency with which each digit appears, so using this I can adjust the frequency with which the script executes by selecting the appropriate values. Interestingly the distribution of digits at first glance seems to obey Benford's Law...

-

use

``````if [ "\$(echo \$RANDOM | cut -c1)" = 3 ]; then
echo "YES" >> ~/result.txt
fi
``````

or even

``````[ "\${RANDOM:0:1}" = 3 ] && echo "YES" >> ~/result.txt
``````
-
This works too! Thank you for showing how it can be done other ways. Selected this as my accepted answer because it fixes the way I was trying to do it, although the other answer provided also works. – Themistocles Dec 2 '11 at 10:30

It's nicer to test if \$RANDOM is smaller than a given number. If you chose 10000,

``````if [ \$RANDOM -le 10000 ]; then
echo "YES" >> ~/result.txt
fi
``````

Will do the trick. Of course you can pick a different number. ("-le" means less-than-or-equals).

-
This works, thanks! – Themistocles Dec 2 '11 at 10:30