suffa
suffa

Reputation: 3796

How to use dd command in bash in loop

I'm not really well versed in bash, but I know a few commands, and can get around somewhat. I'm having trouble writing a script to fill up the flash drive on an external device that is running Ubuntu (embedded Linux).

dd if=/dev/urandom of=/storage/testfile.txt

I want to know when the flash drive has filled up (stop writing random data to it), so I can continue with other operations.

In Python, I would do something like:

while ...condition:

    if ....condition:
        print "Writing data to NAND flash failed ...."
        break
else:
    continue

But I'm not sure how to do this in bash. Thanks in advance for any assistance!

Upvotes: 0

Views: 10646

Answers (2)

clt60
clt60

Reputation: 63892

Try this

#!/bin/bash

filler="$1"     #save the filename
path="$filler"

#find an existing path component
while [ ! -e "$path" ]
do
    path=$(dirname "$path")
done

#stop if the file points to any symlink (e.g. don't fill your main HDD)
if [ -L "$path" ]
then
    echo "Your output file ($path) is an symlink - exiting..."
    exit 1
fi

# use "portable" (df -P)  - to get all informations about the device
read s512 used avail capa mounted <<< $(df -P "$path" | awk '{if(NR==2){ print $2, $3, $4, $5, $6}}')

#fill the all available space
dd if=/dev/urandom of="$filler" bs=512 count=$avail 2>/dev/null
case "$?" in
    0) echo "The storage mounted to $mounted is full now" ;;
    *) echo "dd errror" ;;
esac
ls -l "$filler"
df -P "$mounted"

Save the code to file, e.g.: ddd.sh and use it like:

bash ddd.sh /path/to/the/filler/filename

The code is done with the help from https://stackoverflow.com/users/171318/hek2mgl

Upvotes: 0

anubhava
anubhava

Reputation: 785008

As per man dd:

DIAGNOSTICS
     The dd utility exits 0 on success, and >0 if an error occurs.

That is what you should do in your script, just check the return value after dd command:

dd if=/dev/urandom of=/storage/testfile.txt
ret=$?
if [ $ret gt 0 ]; then
    echo "Writing data to NAND flash failed ...."
fi

Upvotes: 1

Related Questions