2
echo 1 | awk '{ srand(); print int (rand()*67) }'

I get a different o/p everytime I run it. However if I omit the 1 I get same o/p ..why?

  • I can't reproduce this on OS X. With or without the 1 I get random output. – polynomial Oct 4 '11 at 3:10
  • you are right polynomial! – Ankur Agarwal Oct 4 '11 at 3:30
  • 3
    The outcome of srand() varies once per second (it seeds the pseudorandom number generator based on the whole number of seconds since the origin of time), which explains why you might have seen the same output twice if you ran the command twice in quick succession. – Gilles 'SO- stop being evil' Oct 4 '11 at 7:11
6

It prints a random number between 1 and 67. It could also have been written without the echo:

awk 'BEGIN{srand(); print int(rand()*67+1)}'

See the Gnu Awk Users Guide:

srand([x])
Set the starting point, or seed, for generating random numbers to the value x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.