Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.
read /dev/urandom 3

The above is not working..How can I read random bytes from /dev/urandom in bash?

share|improve this question
add comment

3 Answers 3

up vote 10 down vote accepted
random="$(dd if=/dev/urandom bs=3 count=1)"
share|improve this answer
    
@Flimzy,how does $() work? –  linux Jun 23 '11 at 6:07
    
It treats the output of a command like a variable. Note: That's a bashism. If you're not using bash, you may need to use `` instead. `` is more universal, but I think $() is easier to read. –  Flimzy Jun 23 '11 at 6:08
    
@Flimzy,It treats the output of a command like a variable.,you actually mean as string,right? –  linux Jun 23 '11 at 6:14
1  
A variable can be a string... or a number. It treats it as a variable... then depending on context, it's treated like a string, or a number. –  Flimzy Jun 23 '11 at 6:27
    
$() is pretty universal, not bash-specific. BTW, be careful you don't run into limitations on what characters the shell can store in variables -- for example, the version of bash I tested with leaves out nulls (\x00) from the string. –  Gordon Davisson Jun 23 '11 at 13:13
show 2 more comments
head -c 500 /dev/urandom | tr -dc 'a-zA-Z0-9~!@#$%^&*_-' | fold -w 3 | head -n 1

(If you want literal dash characters, the dash character must go at the end of the string).

share|improve this answer
    
He's looking for 3 bytes... –  Chris S Feb 21 '13 at 16:56
1  
3 plus exact pattern –  ADM Feb 21 '13 at 17:05
    
This is excellent. –  Danijel J Jan 31 at 3:28
    
Thats excellent. More then OP asked! –  TheHippo Feb 5 at 12:01
add comment

Try this: dd if=/dev/urandom bs=1 count=3

If you want to put the result in $variable:

variable=`dd if=/dev/urandom bs=1 count=3`

Do note that it'll probably not be printable.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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