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

Re: RANDOM shell expansion



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

To wit:
for i in {1..3}; do (echo $RANDOM) done
17530
17530
17530
vs:
for i in {1..3}; do echo $RANDOM; done
17530
12664
23361

That all makse sense to me. But it still feels weird that when you do something like (my command) >$foo, the expansion of $foo is done in the subshell, even though it's not inside the parentheses.

On Tue, Nov 11, 2025 at 11:03 AM Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
On Tue, Nov 11, 2025 at 3:58 AM Philippe Altherr
<philippe.altherr@xxxxxxxxx> wrote:
>
> The reason for the difference is that Zsh evaluates the redirection in the process of the affected command. echo and false are builtins. They are run and their redirections are evaluated in the running Zsh process. timeout is an external command. It is run and its redirection is evaluated in a forked process.

This is correct, but it's not the whole story.  Zsh defines $RANDOM as
a *repeatable* sequence of random numbers:
     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.

> On Tue, Nov 11, 2025 at 11:28 AM Luis Estrozi <lestrozi@xxxxxxxxx> wrote:
>>
>> I tried this on bash and it works as expected.

Bash does not define RANDOM as repeatable.  Subshells / forks get a
new instantiation of RANDOM with new values.



--
Mark J. Reed <markjreed@xxxxxxxxx>


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