How to create a certain size zipped file

For particular test, sometime I need to create a certain size zipped file, for example, exact 1MB to 10GB etc..

Here are ways I do usually.

Example 1: using dd, but it's not zipped

dd bs=1024 count=1024 if=/dev/urandom of=1MiBtestfile

Example 2: using dd and /dev/random

dd bs=1024 count=1024 if=/dev/random of=1MiBtestfile

Since /dev/random is a pseudorandom number generator, it's naturally 'zipped' file, but you it's too slow to get a even 1MB file, so

Example 3: use split

First, create a bigger file using dd

$dd bs=1024 count=10240 if=/dev/urandom of=./testfile
10240+0 records in
10240+0 records out
10485760 bytes (10 MB) copied, 1.08761 s, 9.6 MB/s

compress it

$bzip2 testfile

then split it

$split -b 1048576 testfile.bz2 1MiBtestfile
$ls -l 1MiBtestfile*
-rw-r--r-- 1 test test 1048576 Dec 19 11:44 1MiBtestfilexaa

You get it.

Example 4: tar Multi-volumes option

This is a trick way, recall in old days, you want to copy a big file to multiple tapes, you use -ML option in tar.

It can also be used to create multiple volume disk files.

tar -ML <unit in 1024bytes> cf <device> mybigfile

You may be asked for next volume, well, you know this is a trick way to create a certain sized zipped file.