Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate a random file using shell script

How can i generate a random file filled with random number or character in shell script? I also want to specify size of the file.

like image 720
Progress Programmer Avatar asked Apr 06 '10 17:04

Progress Programmer


4 Answers

Use dd command to read data from /dev/random.

dd if=/dev/random of=random.dat bs=1000000 count=5000

That would read 5000 1MB blocks of random data, that is a whole 5 gigabytes of random data!

Experiment with blocksize argument to get the optimal performance.

like image 101
Tadeusz A. Kadłubowski Avatar answered Sep 20 '22 20:09

Tadeusz A. Kadłubowski


head -c 10 /dev/random > rand.txt

change 10 to whatever. Read "man random" for differences between /dev/random and /dev/urandom.

Or, for only base64 characters

head -c 10 /dev/random | base64 | head -c 10 > rand.txt

The base64 might include some characters you're not interested in, but didn't have time to come up with a better single-liner character converter... (also we're taking too many bytes from /dev/random. sorry, entropy pool!)

like image 21
Amitay Dobo Avatar answered Sep 18 '22 20:09

Amitay Dobo


A good start would be:

http://linuxgazette.net/153/pfeiffer.html

#!/bin/bash
# Created by Ben Okopnik on Wed Jul 16 18:04:33 EDT 2008

########    User settings     ############
MAXDIRS=5
MAXDEPTH=2
MAXFILES=10
MAXSIZE=1000
######## End of user settings ############

# How deep in the file system are we now?
TOP=`pwd|tr -cd '/'|wc -c`

populate() {
    cd $1
    curdir=$PWD

    files=$(($RANDOM*$MAXFILES/32767))
    for n in `seq $files`
    do
        f=`mktemp XXXXXX`
        size=$(($RANDOM*$MAXSIZE/32767))
        head -c $size /dev/urandom > $f
    done

    depth=`pwd|tr -cd '/'|wc -c`
    if [ $(($depth-$TOP)) -ge $MAXDEPTH ]
    then
        return
    fi

    unset dirlist
    dirs=$(($RANDOM*$MAXDIRS/32767))
    for n in `seq $dirs`
    do
        d=`mktemp -d XXXXXX`
        dirlist="$dirlist${dirlist:+ }$PWD/$d"
    done

    for dir in $dirlist
    do
        populate "$dir"
    done
}

populate $PWD
like image 41
zaf Avatar answered Sep 18 '22 20:09

zaf


Create 100 randomly named files of 50MB in size each:

for i in `seq 1 100`; do echo $i; dd if=/dev/urandom bs=1024 count=50000 > `echo $RANDOM`; done

like image 34
zeugmatis Avatar answered Sep 18 '22 20:09

zeugmatis