Home > Blockchain >  $RANDOM variable doesn't seem to change after output is piped
$RANDOM variable doesn't seem to change after output is piped

Time:09-23

Pretty self-explanatory, but the $RANDOM variable only changes when the output is not piped. Is this a bug in zsh or the result of my lack of understanding somewhere? Here is the result of my commands:

┌──(root㉿linux)-[~/scripts]
└─# echo $RANDOM                             
14103
                                                                                                                                                                      
┌──(root㉿linux)-[~/scripts]
└─# echo $RANDOM
30417
                                                                                                                                                                      
┌──(root㉿linux)-[~/scripts]
└─# echo $RANDOM
3090
                                                                                                                                                                      
┌──(root㉿linux)-[~/scripts]
└─# echo $RANDOM | md5sum | head -c 20
af5655b26ab87e81ef4f
                                                                                                                                                                      
┌──(root㉿linux)-[~/scripts]
└─# echo $RANDOM | md5sum | head -c 20
af5655b26ab87e81ef4f
                                                                                                                                                                      
┌──(root㉿linux)-[~/scripts]
└─# echo $RANDOM | md5sum | head -c 20
af5655b26ab87e81ef4f

Why is this happening? The same script in bash seems to work.

CodePudding user response:

This is expected behavior in zsh. See this mailing list archive

from zshparam:

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

You can solve this by simply accessing $RANDOM again before the piped command.

$ echo $RANDOM | cat
27008
$ echo $RANDOM | cat
27008
$ temp=$RANDOM
$ echo $RANDOM | cat
30572
  • Related