Use the RANDOM
variable of your shell to get a random number, but seed the random number generator with today's date first (if the script hasn't been used since midnight). Then pick that line out of the file.
In other words (Bash below)...
wotd_data="wotd_data.txt"
stamp="$HOME/.wotd-stamp"
stamp_random="$HOME/.wotd-random"
date_now=$( date +"%Y%m%d" )
if [ -f "$stamp" ]; then
date_last=$( <"$stamp" )
else
date_last=0
fi
if [ "$date_last" != "$date_now" ]; then
RANDOM="$date_now"
echo "$date_now" >"$stamp"
else
RANDOM=$( <"$stamp_random" )
fi
number=$RANDOM
echo $number >"$stamp_random"
number=$RANDOM$RANDOM # See the "Edit #2" note below
data_length=$( wc -l <"$wotd_data" )
line=$(( 1 + ( number % data_length ) ))
sed -n "${line}p" "$wotd_data"
This uses a time-stamp file in the user's $HOME
to keep track of when they last ran the command. If it wasn't today, then re-seed $RANDOM
with today's date and write today's date into the file.
EDIT #1: I had to also store the last used random number since $RANDOM
is local to the current shell. The seeding doesn't otherwise carry over to the next invocation of the script. I store that in a separate "random stamp" file. You might want to change this to use only one file for both the date of the last invocation and the last used random number.
EDIT #2: Can anyone spot the problem with my original code? Well, $RANDOM
will never be more than 32767 (16 bits), and the file was said to have more lines than this. This means that maybe using $RANDOM
alone may not be a good idea. This is why I resort to simply concatenating $RANDOM
with itself, generating a longer random number. The seeding and the "random stamp" file is not affected by this.
EDIT #3: Just noticed that the OP requested "the same line every time the script is run on a particular day" (in a comment that my brain didn't grok late last night), which is exactly what my script does not do (it gives the same sequence of lines every day). I'm leaving my solution in here anyway in case it helps someone else with similar issues of preserving the state of $RANDOM
between script invocations.