Shell $ RANDOM seeds not marked in pipelines

This is a strange behavior that I cannot explain. I want to use a shell to generate a predictable sequence of random numbers. I am using $ RANDOM with seed. Here is a test program.

RANDOM=15
echo $RANDOM

This works fine, indicating the same number every time I run it. But if I add a tube to this program, it gives different results every time. Try the following simplified program.

RANDOM=15
echo $RANDOM | cat

I found 2 fixes for the problem (which makes it predictable), but still cannot explain why.

Fix 1

RANDOM=15
x=$RANDOM
echo $x | cat

Fix 2

(RANDOM=15
echo $RANDOM) | cat

I tried Linux and Mac. The behavior is consistent. Can someone explain?

+4
source share
2

, echo $RANDOM | cat, - , , exec() - family. , RANDOM, , .

$RANDOM ( ), ( ).

+7

, (). src bash, variable.c. $RANDOM - " ", , ; , $RANDOM .

// from bash-4.3/variables.c

int
get_random_number ()
{
  int rv, pid;

  /* Reset for command and process substitution. */
  pid = getpid ();
  if (subshell_environment && seeded_subshell != pid)
    {
      seedrand ();    // <<<<==== re-seed!
      seeded_subshell = pid;
    }

  do
    rv = brand ();
  while (rv == last_random_value);
  return rv;
}

Seed - , . . , $RANDOM , .

RANDOM=15
echo $RANDOM $RANDOM
RANDOM=15
echo $RANDOM | cat
echo $RANDOM

15.

+2

Source: https://habr.com/ru/post/1543322/


All Articles