How to read in N random characters from /dev/urandom?

random="$(dd if=/dev/urandom bs=3 count=1)"

head -c 500 /dev/urandom | tr -dc 'a-zA-Z0-9~!@#$%^&*_-' | fold -w 3 | head -n 1

(If you want literal dash characters, the dash character must go at the end of the string as done above, as opposed to *-_).

And to explain what gets done due to the above set of commands:

  1. head -c 500 /dev/urandom: Obtain the first 500 characters (bytes) from /dev/urandom.
  2. tr -dc 'a-zA-Z0-9~!@#$%^&*_-': Remove all but the characters specified in 'a-zA-Z0-9~!@#$%^&*_-' from the output of the first command.
  3. fold -w 3: Format the output of the second command such that it has 3 characters per line.
  4. head -n 1: Display the first line of the result of the third command on stdout.