0

I'm trying to generate a random hex number with an specified length ($length) using the following command:

head -c $length /dev/urandom | xxd -p -u -c $length | tr -d '[:space:]\\'

I've noticed that head -c $length /dev/urandom actually prints the double of the $length value. So if $length=1 the output will be 2 characters long. How can I fix this?

Also why does the input number on xxd -p -u -c $length seems not to affect on the output? meaning I can use either:

head -c 4 /dev/urandom | xxd -p -u -c 20000 | tr -d '[:space:]\\'

or

head -c 4 /dev/urandom | xxd -p -u -c 4 | tr -d '[:space:]\\'

and it will print 8 characters in both cases.

chyxo
  • 19
  • 4
  • 1
    [This](https://stackoverflow.com/questions/34328759/how-to-get-a-random-string-of-32-hexadecimal-digits-through-command-line/34329057#34329057) may help. – Renaud Pacalet Jan 24 '23 at 15:00
  • 4
    `head -c` designates the number of *bytes*; each byte contains two hex digits; consider generating the hex digits and *then* take the `head -c`, eg: `xxd -p -u /dev/urandom | head -c $length` – markp-fuso Jan 24 '23 at 15:05
  • 1
    as for the last question ... `head -c 4` is going to send exactly 4 bytes (or 8 hex digits worth) of data to the next command in the pipeline (`xxd` in this case); if `xxd` only has 4 bytes of input to work with then why would you expect it to generate *more* than 8 hex digits worth of output? – markp-fuso Jan 24 '23 at 15:24

0 Answers0