Skip to content
Home ยป How to Create a File of a Certain Size in Linux?

How to Create a File of a Certain Size in Linux?

  • by

The previous article has explained how to reduce the size of a file in Linux. This article will explain how to increase the size of a file in Linux.

 

Problem

How to create a file of a certain size in Linux?

 

Solution

By default, if you want to create a file, it will use the command:

touch example.txt

 

And the command above will generate an example.txt file with a size of 0 bytes, as shown in the image below:

Create a file in Linux

 

However, sometimes there are situations where you have to create a file of a certain size for a purpose, e.g., you have to create a test.txt file with a size of 2 GB, Then there are several methods to generate such files of a certain size:

1. Using the fallocate command

Use the command below to create a test.txt file with a size of 2 GB:

fallocate -l 2048MB test.txt
Using the fallocate command

 

2. Using the truncate command

Create a test.txt file with a size of 2 GB using the command below:

truncate -s 2048MB test.txt
Using the truncate command

 

3. Using the dd command

To produce a test.txt file that is 2 GB in size, run the command below:

dd if=/dev/zero of=test.txt bs=1M count=2048MB
Using the dd command

 

4. Using the head command

Use the command below to generate a test.txt file of size 2 GB:

head --bytes 2048MB /dev/zero > test.txt
create a file of a certain size
Using the head command

 

5. Using the tail command

Utilize the following command to generate a 2 GB test.txt file:

tail --bytes 2048MB /dev/zero > test.txt
create a file of a certain size
Using the tail command

 

6. Using Perl commands

Below is the command to create a 2 GB test.txt file (the number 2147483648 comes from 2048x1024x1024):

perl -e 'print '0' x 2147483648' > test.txt
create a file of a certain size
Using the Perl command

 

7. Using the base64 command

Create a 2 GB test.tx file, followed by (the number 2147483648 comes from 2048x1024x1024):

base64 /dev/urandom | head -c 2147483648 > test.txt
create a file of a certain size
Using the base64 command

 

Note

To get quick results when creating a file of a certain size, you can use the truncate or fallocate command.

 

References

baeldung.com
tutorialspoint.com
ostechnix.com
unix.stackexchange.com
stackoverflow.com

image_pdfimage_print
Visited 63 times, 1 visit(s) today
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *