Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

4
  • 1
    +1.. As used in a script to assign output to a variable (w/o introducing a newline character and using zero padding for two places): x=$(awk -v min=$min_var -v max=$max_var 'BEGIN{srand(); printf("%.2d", int(min+rand()*(max-min+1)))}') Commented Apr 22, 2019 at 18:35
  • 3
    It's based on time? since I got the same value in 2 consecutive runs... Commented May 5, 2019 at 14:13
  • @ShaiAlon the current time is often used as the default seed value for srand() so usually, yes it's based on time, see Stéphane's sentence about that in his answer. You can get around that by changing the initial seed to a random number with awk -v min=5 -v max=10 -v seed="$(od -An -N4 -tu4 /dev/urandom)" 'BEGIN{srand(seed+0); print int(min+rand()*(max-min+1))}'. You could use $RANDOM instead of od ... /dev/random but then your seed value is in the relatively small range of 0 to 32767 and so you'll probably get noticeable repetitions in your output over time. Commented Aug 9, 2019 at 17:54
  • I've been burned too many times by various awk implementations' bad randomization to trust them, which is why my answer (also portable and pure posix) uses od on /dev/urandom Commented Mar 21, 2024 at 3:17