Generate File of a certain size?

I’d like to generate a file with the name example.file. I could use

touch example.file

but I want the file to be exactly 24MB in size. I already checked the manpage of touch, but there is no parameter like this. Is there an easy way to generate files of a certain size?

Asked By: R_User


You can use dd:

dd if=/dev/zero of=output.dat  bs=24M  count=1


dd if=/dev/zero of=output.dat  bs=1M  count=24

or, on Mac,

dd if=/dev/zero of=output.dat  bs=1m  count=24
Answered By: Paul92

You can use dd:

dd if=/dev/zero of=outputfile.out bs=1024k count=24

Or in case you happen to be using Solaris

mkfile 24m outputfile.out
Answered By: BitsOfNix

Under non-embedded Linux or Cygwin (or any system with GNU coreutils) and FreeBSD:

truncate -s 24m example.file

This creates a file full of null bytes. If the file already exists and is smaller, it is extended to the requested size with null bytes. If the file already exists and is larger, is is truncated to the requested size.

The null bytes do not consume any disk space, the file is a sparse file.

On many systems, head -c 24m </dev/zero >example.file creates a non-sparse file full of null bytes. If head doesn’t have a -c option on your system (it’s common but not in POSIX), you can use dd bs=1024k count=24 </dev/zero >example.file instead (this is POSIX-compliant).

echo; cd $MOUNT_PATH; pwd; ls -la; sleep 1; echo;
WHEN="$(date +%Y-%m-%d_%H-%M-%S)";
fallocate -l 10M $MOUNT_PATH/"$FROM_NODE"_"$WHEN".dump
ls -lha; echo;
Answered By: Pascal Andy

If you don’t care about the content of the file, this is much faster than using dd:

fallocate -l 24M filename

Obviously, using dd for a 24MB file won’t take any time on a modern system, but larger files can be noticeably slow.

Answered By: SArcher

refer other summary:

  • truncate
    • truncate -s 24M example.file
  • fallocate
    • fallocate -l $((24*1024*1024)) example.file
  • head
    • random data
      • head -c 24MB /dev/urandom > example.file
    • zero data
      • head -c 24MB /dev/zero > example.file
  • dd
    • dd if=/dev/urandom of=example.file bs=24MB count=1
      • dd if=/dev/urandom of=example.file bs=4MB count=6
Answered By: crifan
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.