LinuxCommandLibrary

mkfile

Create a file of a specified size

TLDR

Create an empty file of 15 kilobytes

$ mkfile -n [15k] [path/to/file]
copy

Create a file of a given size and unit (bytes, KB, MB, GB)
$ mkfile -n [size][b|k|m|g] [path/to/file]
copy

Create two files of 4 megabytes each
$ mkfile -n [4m] [first_filename] [second_filename]
copy

SYNOPSIS

mkfile [-nv] size[b|k|m|g] filename ...

PARAMETERS

-n
    Do not actually create the file; just print the command that would be executed.

-v
    Verbose mode. Print a message to standard error for each file created.

size[b|k|m|g]
    The size of the file to create. Size is an integer, and can be followed by a suffix of b (bytes), k (kilobytes), m (megabytes), or g (gigabytes).

filename
    The name of the file to create.

DESCRIPTION

The mkfile command creates one or more empty files of the specified size. It's a fast way to pre-allocate disk space. Unlike tools that write to the file to achieve the desired size, mkfile leverages system calls to efficiently reserve the space, making it suitable for scenarios like database setup, virtual machine disk creation, or testing file system behavior. It is important to note that depending on the underlying file system, the created files might be sparse (containing holes) or fully allocated.
The main advantage of mkfile is its speed and efficiency when large files are needed. It is often preferred over alternative methods like using dd to create large files filled with zeros.

CAVEATS

The files created by mkfile might be sparse, meaning they contain holes. The actual disk space occupied may be less than the specified size until data is written into the holes.
The command's availability and behavior may vary slightly across different Unix-like systems.

SPARSE FILES

A sparse file is a type of file that attempts to use file system space more efficiently when storing files that contain large areas of empty space (i.e., composed of long sequences of zero bytes). Instead of allocating disk space for these null bytes, the file system records only the actual (non-null) data and the metadata that indicates where the 'holes' (sequences of null bytes) are located. When the file is read, the file system effectively fills in the holes with zeros, so the reading application sees the file as if it contained the full amount of data, including the null bytes.

EXAMPLE USAGE

To create a 1GB file named 'testfile.img': mkfile 1g testfile.img.
To create verbose 1GB file named 'testfile.img': mkfile -v 1g testfile.img.

SEE ALSO

truncate(1), fallocate(1), dd(1)

Copied to clipboard