Search code examples
bashzsh

$RANDOM being constant when returning it from a function


getRandom () {
  echo $RANDOM
}

getRandomFromGetRandom () {
  echo $(getRandom)
}

Calling getRandom does the expected every time, it returns some random number on each call.

What I'd expect is the same from getRandomFromGetRandom, that a random number being called every time I call getRandomFromGetRandom, but that's not the case. Every time that function is called it returns a constant which changes only when I open another instance of the terminal.


Solution

  • man zshparam says:

    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.

    Since command substitution is performed in a subshell, this explains the repetitive values getRandomFromGetRandom prints. To fix it, reference RANDOM before echoing $(getRandom), like

    getRandomFromGetRandom () {
      : $RANDOM
      echo $(getRandom)
    }
    

    Or seed it (zsh-only; won't work on yash)

    getRandomFromGetRandom () {
      RANDOM= echo $(getRandom)
    }