59

When trying to redirect to /dev/null and /dev/zero, the output it is discarded. It seems both /dev/null and /dev/zero accept and discard all input. So, what is the difference between /dev/null and /dev/zero?

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Pandya
  • 23,898
  • 29
  • 92
  • 144

1 Answers1

91

Yes, both accept and discard all input, but their output is not the same:

  • /dev/null produces no output.
  • /dev/zero produces a continuous stream of NULL (zero value) bytes.

You can see the difference by executing cat /dev/null and cat /dev/zero.

  • Try cat /dev/null > file and you will find an empty file.

  • Now try cat /dev/zero > file, while watching the size of the file (watch -n 1 du -h file) continuously increase. This is because reading from /dev/zero gives an endless stream of \0 (null) characters.

Use dd to visualize the difference more appropriately:

$ dd if=/dev/null of=file count=10
0+0 records in
0+0 records out
0 bytes (0 B) copied, 0.000276193 s, 0.0 kB/s

$ dd if=/dev/zero of=file count=10
10+0 records in
10+0 records out
5120 bytes (5.1 kB) copied, 0.00090775 s, 5.6 MB/s

/dev/zero is used to create dummy files or swap.

Also visit:

Pandya
  • 23,898
  • 29
  • 92
  • 144
  • Also see http://thecodelesscode.com/case/6 – kojiro Jan 10 '16 at 16:37
  • 3
    Worth noting: `mmap`ping `/dev/zero` with `MAP_PRIVATE` is the "portable" way to obtain an anonymous memory mapping (in the absence of extensions like `MAP_ANON`). – nneonneo Jan 10 '16 at 23:11
  • 12
    Perhaps not obvious to the casual reader is just *how* `/dev/null` produces no output: It signals EOF immediately. – Peter - Reinstate Monica Jan 11 '16 at 04:30
  • 2
    Is there a device that gives all ones? – Aaron Franke Sep 28 '19 at 02:07
  • 5
    hi @AaronFranke, Oh sure! `:-)` Consider output of `/dev/zero` as a stream of _potential_ all-ones bytes: we just need to replace each all-zeros byte with an all-ones byte. An all-ones byte is `377` in octal (as `printf '%o\n' $((2#11111111))` tells us); **`tr '\000' '\377' /tmp/all-ones.dat `** will swiftly generate a huge pile of all-ones bytes. – Vainstein K Jan 12 '21 at 06:03