Shell Script Random Variable
Ive been writing games for my own personal pleasure in unix shell script, ive been cutting the seconds column off of date inorder to produce a random effect, is there a better way to get a random variable?
|
The RANDOM shell variable can be used for random numbers once seeded. This is from the bash man page:
Quote:
Code:
RANDOM=`date '+%s'` |
Quote:
|
What type of system are your on, Linux? Which shell are you using. The example I gave was for bash.
Code:
#!/bin/sh |
Not linux Unix...
|
Quote:
cheers Jamie... |
I dont really know what shell Im in. I would guess bash.. is there a way to find out?
|
Try:
echo $SHELL or cat /etc/passwd | grep username Where username is your login name on the machine. Look at the last entry. It sould be your shell. |
maybe echo $RANDOM can help
|
1 - 9 aren't picked as much as 10 - 60?
I ran the code below on Linux in a loop and found that the output is indeed random between 10 and 60, but isn't between 1 and 9. Anyone care to explain why this is and if there is a way to get a true random value between say 0 and 60?
#!/bin/bash RANDOM=`date '+%s'` while true ; do x=$[ ($RANDOM % 60) + 1 ] echo $x >> /tmp/$x done Looking at the results with the command below always shows 1 to 9 getting the lowest hits. ls -Sl /tmp |
For true random numbers you must use '/dev/urandom' like this:
Code:
dd if=/dev/urandom count=1 2> /dev/null | cksum | cut -f1 -d" " That's the neatest way of doing it :) (heck I don't even know what it's doing). My way is just use python: Code:
import os |
Quote:
You write the number itself to a file. When you write a single digit number (1-9) only a single character is written to the file. So the file sizes for single digit number grows twice as slow as for two-digit numbers (then two characters are written at one hit). Then you sort the files by file size with "ls -lS"... |
To make use of /dev/urandom in bash scripts I wrote this C program once:
Code:
/* devrandom - shell utility for generating random numbers using /dev/urandom */ |
Quote:
whenever you think you have found a unix bug, you almost certainly have NOT! all these tools have been around for years and it is unlikely that you have found a feature. so always double check your conclusion. ;) |
Random issue
Thanks for the replies.
You're absolutely right, the way I was measuring the success of my script was wrong. Once I wrote out the same single character for all files, true random values returned throughout. Thanks for your time. Simmo |
All times are GMT -5. The time now is 11:32 AM. |