A Simple BASH Script to Create a File of Given Size


We can use the dd command to generate a file size of given bytes however the parameters are not straighforward.

The “if=” specifies the input data (usually from /dev/zero or /dev/random) – and “of=” specifies the output (the target file). The count and bs (blocksize) multipled together will be the final output size.

Hence, here is a bash script that wraps the feature:

1
2
3
4
5
6
7
8
9
#!/bin/bash
# name this mkfile.sh
 
if [[ -z "$1" || -z "$2" ]]; then
    echo Usage: $0 bytes filepath
    exit 1
fi
 
dd if=/dev/zero of=$2 count=1 bs=$1
#!/bin/bash
# name this mkfile.sh

if [[ -z "$1" || -z "$2" ]]; then
    echo Usage: $0 bytes filepath
    exit 1
fi

dd if=/dev/zero of=$2 count=1 bs=$1

For example – to create a file size of 1KB simply do this:

1
$ ./mkfile.sh 1024 1kb.bin
$ ./mkfile.sh 1024 1kb.bin

That will produce this:

1+0 records in
1+0 records out
1024 bytes (1.0 kB, 1.0 KiB) copied, 0.000211357 s, 4.8 MB/s

1
2
$ ls -lh 1kb.bin
-rw-r--r-- 1 root root 1.0K May 19 19:50 1kb.bin
$ ls -lh 1kb.bin
-rw-r--r-- 1 root root 1.0K May 19 19:50 1kb.bin

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
210 words
Last Post: Teaching Kids Programming - Flip One Digit via Greedy Algorithm
Next Post: Teaching Kids Programming - Rotation of Another String

The Permanent URL is: A Simple BASH Script to Create a File of Given Size

Leave a Reply