Create a number of random-content, random-size files in Bash

Not likely to get a proper post out tonight, unfortunately. So here’s a little snippet of Bash code I’m working on, for the implementation of a new clustered file system for work. For stress-testing, I’m going to need to create a bunch of little files of random contents and sizes, and see whether the clustering works properly. Here’s how I’m going to do it.

#!/bin/bash
#generate random files

if [ ! $# -gt 0 ]; then
echo "usage: $0 <numfiles> [<blocksize> <maxblocks>]"
echo " <numfiles>: number of files to create,"
echo " <blocksize>: size of file blocks (default 1024 bytes)"
echo " <maxblocks>: maximum number of blocks per file (default 100)"
echo ""
echo "Parameters after the third provided number are ignored."
echo ""
exit
fi

NUMFILES=$1
if test "$2" == ""; then
BLOCKSIZE=1024
else
BLOCKSIZE=$2
fi
echo Using blocksize $BLOCKSIZE

if test "$3" == ""; then
MAXBLOCKS=100
else
MAXBLOCKS=$3
fi
echo Using max blocks $MAXBLOCKS

for I in $(seq 1 $NUMFILES)
do
echo $((($RANDOM % $MAXBLOCKS) +1))
dd if=/dev/urandom of=testfile.$I.$RANDOM.bin bs=$BLOCKSIZE count=0 seek=$((($RANDOM % $MAXBLOCKS) + 1))
done

Remember, when you create a file using /dev/urandom, don’t ever use the cat command to read its contents in a shell, because you’re liable to mangle your shell’s text output and all text thereafter might get mangled too, until you close that terminal and reopen. If you’re running a headless server, you might even have to reboot it, which probably isn’t a good idea.

{advertisement}
Create a number of random-content, random-size files in Bash
{advertisement}