It is a small story.
In bash, you can randomly get numbers from 0 to 32767 by using the environment variable $ RANDOM
.
For example, to randomly display numbers from 0 to 3, combine the modulo operator symbols %
as follows:
Randomly display numbers from 0 to 3
echo $((RANDOM % 4))
This is the number from 5 to 59.
Randomly display numbers from 5 to 59
echo $((5 + RANDOM % 55))
The explanation of this area was much easier to understand in [Randomly do it with a shell script], so please refer to that.
The main subject. Suppose the following cron is defined on the last line:
00 2 * * * /home/mindwood/foo.sh > /dev/null 2>&1
It is set to start at 2:00 am, but I would like to set this to start from 0:05 am to 3:59 am and give it a range. On top of that, I want to avoid just every hour (1 am, 2 am ...).
Here is the one liner to rewrite.
H=$((RANDOM%4));M=$((5+RANDOM%55));sed -i -e '$s/^[0-9]\+ [0-9]\+/'$M' '$H'/' /var/spool/cron/crontabs/root
For example, it is updated as follows.
43 1 * * * /home/mindwood/foo.sh > /dev/null 2>&1
If you don't like this time, you can start over again.
Note that $
in sed
represents the last line.
For more information on sed
, please refer to [How to write in this case with sed?].
Recommended Posts