Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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...

share|improve this question
up vote 1 down vote accepted


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

or even

[ "${RANDOM:0:1}" = 3 ] && echo "YES" >> ~/result.txt
share|improve this answer
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 

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

share|improve this answer
This works, thanks! – Themistocles Dec 2 '11 at 10:30

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.