Linux: Create file of a given size

Updated . Posted . Visible to the public.

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

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.

Profile picture of Arne Hartherz
Arne Hartherz
Last edit
Daniel Straßner
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2011-07-18 10:35)