33

I know how to create an empty file:

touch /var/tmp/nullbytes

but how can I create a 1MB file that only contains nullbytes on the commandline with bash?

rubo77
  • 28,966
  • Relates SU question: http://superuser.com/q/609020/151431 – terdon Nov 26 '13 at 16:10
  • 1
    +1. Interesting question. Could someone kindly elaborate in which scenarios would such a file be required..? – Kent Pawar Nov 27 '13 at 18:35
  • 1
    I needed it to simulate a crash on chkrootkit: http://unix.stackexchange.com/questions/86866/chkrootkit-throws-signal-13-when-searching-through-var-tmp/102580?noredirect=1#comment156784_102580 – rubo77 Nov 28 '13 at 12:35

2 Answers2

67

With GNU truncate:

truncate -s 1M nullbytes

(assuming nullbytes didn't exist beforehand) would create a 1 mebibyte sparse file. That is a file that appears filled with zeros but that doesn't take any space on disk.

Without truncate, you can use dd instead:

dd bs=1048576 seek=1 of=nullbytes count=0

(with some dd implementations, you can replace 1048576 with 1M)

If you'd rather the disk space be allocated, on Linux and some filesystems, you could do:

fallocate -l 1M nullbytes

That allocates the space without actually writing data to the disk (the space is reserved but marked as uninitialised).

dd < /dev/zero bs=1048576 count=1 > nullbytes

Will actually write the zeros to disk. That is the least efficient, but if you need your drives to spin when accessing that file, that's the one you'll want to go for.

Or @mikeserv's way to trick dd into generating the NUL bytes:

dd bs=1048576 count=1 conv=sync,noerror 0> /dev/null > nullbytes

An alternative with GNU head that doesn't involve having to specify a block size (1M is OK, but 10G for instance wouldn't):

head -c 1M < /dev/zero > nullbytes

Or to get a progress bar:

pv -Ss 1M < /dev/zero > nullbytes
  • Don't use truncate for creating an empty file to be used as swap volume… this will not work! Use dd in this case instead. – Elias Probst Nov 26 '13 at 12:03
  • 1
    @EliasProbst, ITYM copy from /dev/zero instead, do not use a sparse file. dd can create sparse files as I showed as well. – Stéphane Chazelas Nov 26 '13 at 12:08
  • 3
    fallocate is the best and fast way to create because it reserves the space and do it fast but it doesn't bother to write anything (http://stackoverflow.com/questions/257844/quickly-create-a-large-file-on-a-linux-system) – curratore Nov 26 '13 at 12:23
  • ...or bs=1kx1k. Or <&1 dd bs=1kx1k conv=sync,noerror count="$rpt" | cat >file for the literal write to disk thing. Not 100% on how much efficiency might be lost in forcing the read error, though. – mikeserv Jun 15 '15 at 04:03
32
dd if=/dev/zero of=/var/tmp/nullbytes count=1 bs=1M
Zelda
  • 6,262
  • 1
  • 23
  • 28