Linux Command Reference ยท Special Files and Directories
The /dev/zero and /dev/urandom devices
Reference for /dev/zero, /dev/urandom and /dev/random: create zero-filled files, generate random bytes and passwords, the difference between the devices, and safe uses.
Three character devices act as endless data sources. /dev/zero produces an unlimited stream of zero bytes. /dev/urandom and /dev/random produce random bytes from the kernel's cryptographic random number generator.
Use /dev/zero to make blank files and test disk speed, and /dev/urandom to create keys, tokens, salts and test data. On modern kernels (5.6 and later) both random devices give the same quality of randomness once the generator is initialized at boot.
head -c 1M /dev/zero > blank.img head -c 16 /dev/urandom | base64
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
| Device | Reads give | Notes |
|---|---|---|
/dev/zero |
Endless zero bytes (\0) |
Writes are discarded, like /dev/null. |
/dev/urandom |
Random bytes, never blocks | Right choice for nearly all uses. |
/dev/random |
Random bytes | On Linux 5.6+ blocks only until the generator is first seeded at boot; older kernels blocked when the "entropy estimate" ran low. |
/dev/full |
Nothing | Every write fails with "No space left on device"; handy for testing error paths. |
Edge cases: reading never reaches end-of-file, so always bound the read with head -c, dd count= or a pipeline that stops. tr -dc on /dev/urandom may need LC_ALL=C to avoid "Illegal byte sequence" errors in some locales.
Usage notes
- Pick
/dev/urandom. It is the standard source for keys and tokens./dev/randomadds nothing on current kernels, and on old ones it could stall scripts. getrandom(2)is the program interface. Languages call it for you (secretsin Python,crypto.randomBytesin Node).$RANDOMis not secure. The Bash variable is a simple generator, fine for games and test data, wrong for passwords.- Modulo bias.
n % 100on a random 16-bit number slightly favors small results. For uniform values useshuf -i 0-99 -n 1or a tool that handles it. - Wiping.
dd if=/dev/zero of=fileoverwrites data, but SSDs, journaling and snapshots may keep copies; use encryption instead. Seeshredanddd. - Sparse files:
truncatecreates a file that looks large but occupies no blocks, while copying from/dev/zeroallocates real ones.
Related
/dev/null,dd,truncate,od- Lessons: Binary and hex tools, Disks and logs