0

I think I found a really odd bug in Bash's random number generator ($RANDOM).

Showing is easier than telling, so here's what happens:

The goal is to get random digits. If I execute this, I get 20 random digits as expected.

for i in {1..20}; do echo $((RANDOM % 10)); done

But if the echo statement is in a script, I get a really odd pattern of digits.

$ cat randomtest
#!/bin/bash
echo $((RANDOM % 10))

$ for i in {1..20}; do ./randomtest; done
9
8
8
6
7
5
5
4
4
2
3
1
1
1
0
0
8
9
7
7

What in the world is going on?

System information:

  • Mac OS X 10.10.2
  • GNU Bash, version 4.3.30(1)-release (installed via Homebrew)
  • Fine here .... have you run it many times? – MiJyn Mar 9 '15 at 2:35
  • Yes, and it gives the same odd skipping downward pattern every time. – stephenwade Mar 9 '15 at 2:36
  • @MiJyn edited to add system information. I'm on Mac OS X, but using GNU Bash via Homebrew. – stephenwade Mar 9 '15 at 2:39
0

Well, I feel silly.

The problem was that /bin/bash is OS X's default Bash 3.2. Homebrew installs Bash to /usr/local/bin/bash, which is what I'm using in my terminal. If I change the shebang to that, it works as expected.

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.