osx lion - Have a script execute a command randomly every now and then

06
2014-04
  • Themistocles

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

  • Answers
  • rush

    use

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

    or even

    [ "${RANDOM:0:1}" = 3 ] && echo "YES" >> ~/result.txt
    
  • Adrian Ratnapala

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


  • Related Question

    Execute a command and put the results into a variable... all in a bash script
  • CamelBlues

    I'm working on a bash script that backs up a configuration file before copying over a new file.

    Here's what my snippet looks like:

    mv ~/myStuff.conf  ~/myStuff.conf.bak
    cp ~/new/myStuff.conf ~/myStuff.conf
    

    Every time this script is run, I'd like there the backup to have a unix timestamp in the filename. I tried this

    DATEVAR=date +%s
    mv ~/myStuff.conf  ~/myStuff.conf.$DATEVAR.bak
    

    But this doesn't work, since the date function doesn't execute and bash sees it as a string, and the resulting file ends up being

    myStuff.conf.date+%s.bak
    

    Any ideas on how to get the results of the date function into a variable?


  • Related Answers
  • Rich Homolka

    This is possible with command substitution.

    DATEVAR=$(date +%s)