How do you generate random strings from /dev/random?
Of course every language has some kind of random
library... But can you generate custom random strings with just basic CLI tools?
For example, we have /dev/random
which provides a stream of random values... But they're random bytes, so a lot of them are non-printable or special characters. If I want a random number of random alphanumeric string, how do I get that from /dev/random
?
1 answer
/dev/random
is a stream of every possible value. You're supposed to filter it to take the ones you want. This is efficient, although if the values you want are such that only, say, 1% of what comes out of /dev/random
is acceptable, then it will obviously take 100x longer to generate them. But luckily /dev/random
is very fast.
First, the foreword: cat /dev/random
(yes, useless cat, whatever) will produce a forever stream of random data. This isn't very useful, usually you want a limited stream, you do it with head
:
$ cat /dev/random | head -c 20
NL(c%t6ޖ[\{I⏎
This is taking 20 random chars. head
is nice in that, even though the input is infinite, head
will shut it off once it has what it needs (well, your shell will, whatever). You'll note it's actually 12 chars - head is getting 20 bytes, then they get rendered by my shell, some end up displayed as multi-byte Unicode chars. This unicode business will stop mattering in a minute. The newline is just added, it's not coming from /dev/random
.
We now need to throw out characters we don't want. This must be some incantation that will produce only "good" chars, so that head
can collect 20 of them and exit. The OG way is tr
:
$ cat /dev/random | tr -cd A-Za-z0-9 | head -c 20
yBJ1Uh7yatwdZmgxVK8C⏎
-c
is --complement
aka invert. -d
is --delete
. So we have "delete everything that is not A-Za-z0-9
".
0 comment threads