BVCGAAV
BVCGAAV

Reputation: 299

Bash script to read from /dev/urandom

I want to make bash script that sends to stdout a file image containing only ASCII writable characters. My script should receive and accept only one argument containing the number of octets that should be read from /dev/urandom.

So, I need to read a given number of octets from /dev/urandom to create a file image to send to stdout.

I have this:

!/usr/bin/env bash

X=1

if [ $X -eq 0 ]; then
    echo "Error: An argument is needed"
else
    strings /dev/urandom    
    echo the result
fi

I'm checking if there's any argument and, if there is, read the /dev/urandom. Of course this is just a sketch.

I was told there is a command called strings that reads and extracts sequences of characters from any file, but I've checked on the internet and I can't find much info about it.

So my question is: How do I read the number of octets given in the arguments from /dev/random so that I can put them in stdout (I know how to put on stdout :) )

Upvotes: 2

Views: 4566

Answers (1)

William Pursell
William Pursell

Reputation: 212544

strings is not what you want. If you just want random characters restricted to a particular set, filter out what you do not want. To get $num alphanumeric chars from /dev/urandom, you can do:

tr -dc A-Za-z0-9 < /dev/urandom | dd bs=$num count=1 2> /dev/null

or

tr -dc '[:alnum:]' < /dev/urandom ...

Note that this is not strictly portable. Although the standard for tr states that it should work on any input file, my version is throwing the error 'Illegal byte sequence'. Another option is:

perl -pe 's/[^a-zA-Z0-9]//g' /dev/urandom | dd bs=$num count=1 2> /dev/null

Upvotes: 7

Related Questions