Create a large file filled with zeros on Linux

Sometimes you need a large file for testing purposes or just to take up space that should not be available on the file system.

There are several options on how to generate such a file on Linux:

  • The traditional method is using dd, setting if (in file) to either /dev/null or to /dev/random.
  • A more modern method is using truncate, which generates sparse files, which may be or may not be what you want.
  • An alternative modern method is using fallocate, which does not generate sparse files

Let’s say you want to create a 500 GibiByte file:

Using dd and filling it with 0 is done like this:

 dd if=/dev/zero of=500gbfile bs=500M count=1024

Using truncate (which will be read as a file containing 0s but not actually use that much space) is done like this:

truncate -s 500G 500gbfile

Using fallocate (filling it with 0s and actually allocating the space) is done like this:

fallocate -l 500G 500gbfile

Source: This article on StackOverflow.