Last Updated: February 25, 2016
· twisol

Generate random ASCII from the shell

Since I'm usually full-screened in Chrome, I normally ask my LastPass extension for some random bytes, but if you ever find yourself in need of some noise from the terminal, this can be pretty handy.

Using Ruby, and with the Ascii85 gem installed:

cat /dev/urandom | ruby -rubygems -rascii85 -e "puts Ascii85.encode([0].to_i))[2...-2]" 12

/dev/urandom is a reliable source of random data provided by most UNIX-based operating systems. Its quality isn't always as high as /dev/random, which is more picky about the guarantees it provides, but it's still suitable for cryptographic needs.

The Ascii85 algorithm is used to convert from the pure noise generated by /dev/urandom, which can contain non-printable characters, and produce clean ASCII strings without wasting any of the random data.

The 12 at the end is the number of bytes you want to read from /dev/urandom, not the length of the output string. 12 random bytes appears to produce 16 result bytes. If you remove the number and put this line in a shell script, you can pass in whatever number you like.

3 Responses
Add your response


That's not shell, that's ruby. Here's the shell-only equivalent to this; for those who, like me, don't have ruby and thought this protip was about shell:

$ cat /dev/urandom | tr -dc '0-9a-zA-Z!@#$%^&*_+-' | head -c 15
over 1 year ago ·

As the above won't work by default in OSX, this might also be handy:

cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 16 </code>

If you need a newline after the command runs (for copy/paste funtimes), try this:

echo `cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 16`

over 1 year ago ·

Hey, thanks for the great improvements! I admit, my shell-fu is sub-par - I was mainly looking for a way to generate random strings from the shell, not necessarily in shell script. I went ahead and added the ruby tag to reduce confusion.

over 1 year ago ·