Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: random once but not twice

On Sat, 11 Nov 2017 23:46:07 +0100
Emanuel Berg <moasen@xxxxxxxx> wrote:
> Emanuel Berg wrote:
> > echo $(echo $RANDOM) # always the same
> OK, I learned on #zsh@freenode that $RANDOM
> doesn't do anything but is inherited from the
> parent shell where there has been no access and
> thus no new value.
>     : $RANDOM; vid=$(random-video $vid_dir)

You can also work around with the following rand48 function.

(rand48; print $REPLY)
(rand48; print $REPLY)


# Genrate a 48-bit pseudo-random number as a floating point value between
# 0 and 1 in $REPLY.
# This version is slow but works aroud the fact that the random number
# seed doesn't propagate back from a subshell by storing the seed in
# a file.
# You can speicify a file name, else ${ZDOTDIR:-~}/.zsh-rand48-seeed is used,
# but if using the default be careful about simultaneous accesses from
# multipe shells.

zmodload zsh/mathfunc

local file=${1:-${ZDOTDIR:-~}/.zsh-rand48-seed}
local seed

if [[ -f $file ]]; then

typeset -g REPLY=$(( rand48(seed) ))

print $seed >$file

Messages sorted by: Reverse Date, Date, Thread, Author