Quickly Generate Dummy Files Of Different Sizes From Linux Command Line

It can be useful to create sample blank or dummy files of various sizes for testing and other purposes. In Linux, there are different ways to do this from the command line but an easy one for this is to use the fallocate command.

This command simply allocates disk space for files based on the size specified. The common syntax for this is :

fallocate -l filesize filename

The -l parameter is the input length parameter. Although you can convert and specify the exact bytes to be used for this, the fallocate command allows you to specify a human-readable format like KB, MB, GB, and so on.

Let’s take a look at some of the different random-sized files that can be created with the fallocate command.

3 KB file:

creating a 3KB file using the fallocate command

fallocate -l 3KB sample3KBfile

Listing the file size using the ls -lh command will show that it is created as required.

1 MB file:

fallocate -l 1MB sample1MBfile

creating a 1 MB file using the fallocate command

 

137 MB file:

Not just round numbers, you can specify any input file size to be created.

fallocate -l 137MB sample137MBfile

creating a 137 MB file using the fallocate command

 

300 MB file:

fallocate -l 300MB sample300MBfile

creating a 300 MB file using the fallocate command

 

1 GB file:

fallocate -l 1GB sample1GBfile

creating a 1GB file using the fallocate command

You can also check the other parameters that can be used for fallocate by using the man command:

man fallocate

man page for fallocate

Bash shell script for creating sample files using fallocate:

As with Linux commands, you can also create a Bash shell script that creates such sample blank files.

For example, to create five sample files of 5MB each; here is how to do it using the shell script named autofiles.sh:

Open any text editor like vi or nano ( nano in this example):

nano autofiles.sh

opening nano text editor in Linux

Then paste the following code:

#!/bin/sh

for i in file1 file2 file3 file4 file5

do

fallocate -l 5MB test"$i"

done

echo "Dummy files of 5MB created"
ls -lh

Bash script for generating sample 5 MB files using fallocate

This shell script uses a for loop to take in five file names and combines it with the fallocate command to generate 5MB files. (Here is a quick primer on how to make Bash shell scripts.)

Save the script and make it executable:

making the Bash script executable

chmod a+x autofiles.sh

Run the shell script:

./autofiles.sh

sample files generated using the Bash script that uses fallocate

The sample blank files will be generated by this script and be of 5MB each. The ls -lh command added at the end of the script will list them with their sizes.

Overall, the fallocate command is a quick way to create huge sample files directly from the Linux command line and is easy to remember and use.

All done.

Comments are closed.