Cmd 'cat /dev/urandom' not closing cleanly

Hi

I'm running the following command to generate a random password in a KSH script on a RHEL Linux VM but for some reason the cmd is not being closed and it's causing problems on the host.

PASSWORD="$(cat /dev/urandom | tr -dc "a-zA-Z0-9" | fold -w 16 | head -1)Aa0!"

The code worked as expected but the side effects were definitely unexpected. Any idea how I can enhance this to ensure the urandom stream gets closed after it's been called and therefore prevent the server from becoming overloaded?
Many thanks.

/dev/random supplies an seemingly infinite number of random bytes (in fact limited to 32MB since linux 3.16), so your cat won't finish soon if at all,as the random generator won't send an EOF.

(c.f. man random ), so you might want to read that, of limit the byte count yourself, e.g. by using

dd if=/dev/urandom count=40 bs=1

in lieu of cat . Or, why not use bash 's $RANDOM variable?

1 Like

You are right that head should send a SIGPIPE to fold that should send a SIGPIPE to tr that should send a SIGPIPE to cat .
And each program in the chain should terminate.
It's not reliable though, a signal *can* get lost, especially if the system is very busy. If this also happens on an idle system then there is a bug somewhere (in one of the programs or in the shell's pipe handling).
In one of my old scripts (using /bin/sh for many LUnix platforms) I had limited it with

dd if=/dev/urandom dd bs=1 count=12000 | tr ...

and, for safety, if the resul string was too short, I repeated it in a loop.