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

Re: $RANDOM initial state doesn't change



On Tue, Feb 24, 2015 at 12:27 AM, Jan Larres <jan@xxxxxxxxxxxxxx> wrote:
> On 24/02/15 09:22, Timo Sirainen wrote:
>> I was trying to use $RANDOM for a simple 1/0 check, but it kept failing.
>> After a while I realized a new subshell always gives the same $RANDOM
>> result:
>>
>> % for i in {1..10}; do echo `echo $RANDOM`; sleep 1; done
>> 13490
>> 13490
>> 13490
>> 13490
>> 13490
>> 13490
>> 13490
>> 13490
>> 13490
>> 13490
>>
>> Surely it should be more random than that?
>
> From the manual:
>
> RANDOM <S>
>        A  pseudo-random  integer  from 0 to 32767, newly generated each
>        time this parameter is referenced.  The random number  generator
>        can be seeded by assigning a numeric value to RANDOM.
>
>        The   values   of   RANDOM   form   an  intentionally-repeatable
>        pseudo-random sequence; subshells  that  reference  RANDOM  will
>        result  in  identical  pseudo-random  values unless the value of
>        RANDOM is referenced or seeded in the parent  shell  in  between
>        subshell invocations.
>
>
> $ for i in {1..10}; do echo $(echo $RANDOM) $RANDOM; done
> 30686 30686
> 8933 8933
> 4452 4452
> 6983 6983
> 21425 21425
> 27288 27288
> 18721 18721
> 22501 22501
> 1008 1008
> 29465 29465

You can use anonymous functions to always evaluate $RANDOM in the
parent shell (unless of course the whole loop is subshelled),
% for i in {1..10}; do () { echo $(echo $1) $2 } $RANDOM $RANDOM; done

-- 
Mikael Magnusson



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