Bash Random Number
Hey all,
I'm trying to generate a random number in bash: #!/bin/bash number=$RANDOM echo $number This works fine if you want a number in the 0 - 32767 (16-bit integer) range. I need a larger number in the -2147483648 to 2147483647 (32-bit integer) range. Is there another function like $RANDOM that provides a random number in this larger range. I've been looking for a while now and just keep turning up $RANDOM. Thanks for any help, -KARL |
You should have used the tags. I just explained this in detail and put the random+number tag on the post.
http://www.linuxquestions.org/questi...86#post2547786 Please use the site search features before creating a new post. |
Yeah, that totally doesn't answer my question. I did search before posting, and only found other hackish solutions like the one you referred me to. While that solution could possibly solve a similiar problem.
I am not looking for a loop that gives me any x number of 0-9 integers, of course I could do that. My question is: "Is there another function like $RANDOM that provides a random number in this larger range?" -2147483648 to 2147483647 (32-bit integer) There may not be, and the only solution may be to write your own, but I'd rather seek out built in first. |
First, 0-32767 is only 15 bits.
You should take 3 $RANDOM numbers and shift bits to fill a 32 bit integer. Code:
random32=$(( ( ($RANDOM & 3)<<30 | $RANDOM<<15 | $RANDOM ) - 0x80000000 )) |
http://en.wikipedia.org/wiki/16-bit
I suppose I should have specified +-32767. Thank you for the reply, I like the direction you suggested. I'm still going to look around a bit for a built in function, although at this point it's looking bleak. |
For random numbers of arbitrary length I once created this bash function:
Code:
#!/bin/bash On the downside this function is not very fast.. |
Quote:
Oh wait. That's what the - 0x80000000 is about, isn't it? |
All times are GMT -5. The time now is 07:19 AM. |