how to read n random characters from /dev/urandom

If you want to create random chars in a bash script – e.g. to generate a password – you can get these chars from /dev/urandom or /dev/random. It can be very useful in automated deployments to generate a new good password with each deployment.

The difference between /dev/random and /dev/urandom is basically that /dev/random will only output something as long as enough entropy is collected on the systems entropy pool – /dev/urandom will always print some (less random) output.

To output 10 random chars you can use the following command – but these characters might not be printable.

print 10 random characters from /dev/urandom

cat /dev/urandom | head -c 10


echo `dd if=/dev/urandom bs=10 count=1 2>/dev/null`

assign 10 random characters from /dev/urandom to a variable

rand=`cat /dev/urandom | head -c 10`

armor / encode n random characters from /dev/urandom with base64

If you want all characters to be printable, you can encode the output with base64. Due to the padding of base64 the output might be longer than the string coming from /dev/urandom.

echo `dd if=/dev/urandom bs=12 count=1 2>/dev/null |base64`