Read more

Linux: Create file of a given size

Arne Hartherz
July 18, 2011Software engineer at makandra GmbH

Sometimes you need a file of some size (possibly for testing purposes). On Linux, you can use dd to create one.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

Let's say you want a 23 MB file called test.file. You would then run this:

dd if=/dev/zero of=test.file bs=1048576 count=23

The block size (bs) is set to 1 MB (1024^2 bytes) here, writing 23 such chunks makes the file 23 MB big.\
Adjust to your needs.

This linux command might also come in handy in a Ruby program. It could be used like:

mb = 23
mb_string, _error_str, _status = Open3.capture3('dd if=/dev/zero bs=1048576 count=1')
tempfile = Tempfile.open('some_file.txt') do |file|
  mb.times { file.write(mb_string) }
  file
end

Fun fact

Using /dev/zero for input writes zeros only, making the output file incredibly well compressible. If you want the opposite, just use /dev/urandom.

Posted by Arne Hartherz to makandra dev (2011-07-18 12:35)