Monday, August 18, 2014

Block device tester bash script.



First argument is the block device to test.

Requires the dd command and /dev/urandom to be present.


#! /bin/bash
echo -e "\033[1m\E[36;41m\E[5m\033[4m!!!!!!!!WARNING!!!!!!!!\E[0m\E[0m\033[0m\033[0m\E[36;41m\033[1m\033[4m This will erase $1 completely!! Do you want to continue?(y/n) \033[0m\033[0m\E[0m"
read decision
if [[ "$decision" != y ]]
then
 exit
fi
unset decision
# Tests block device.
# First argument -- block device.
#stores size of device in bytes.
declare -i size
declare -i progress
declare -i total_blocks
declare -i remainder_size
progress=0
size=$(blockdev --getsize64 $1)
#Data will be written in 10MB blocks 
total_blocks=$(($size/10485760))
#block count starts from 0
total_blocks=total_blocks-1
# size may not be a multiple of 10
remainder_size=$(($size%10485760))
# Create a random file for testing
dd if=/dev/urandom of=/tmp/"$0_tmp_file" bs=512 count=20480
chksum=$(sha1sum /tmp/"$0_tmp_file" | cut -d ' ' -f1)
while [[ $progress -le $total_blocks ]]
do
 dd if=/tmp/"$0_tmp_file" oflag=direct of=$1 bs=10M seek=$progress
 if [[ $(dd if=$1 iflag=direct skip=$progress bs=10M count=1 | sha1sum | cut -d ' ' -f1) = $chksum ]]
 then
  echo "$((progress*10)) to $(((progress*10)+10)) OK"
 else
  echo "Checksum failed between $((progress*10)) to $(((progress*10)+10))"
 fi
 progress=progress+1
done
# Test remaining blocks, not a multiple of  10M
if [[ $remainder_size -gt 0 ]]
then
# $progress does not needs to changed. Since progress -1 does exist, currently $progress points to a location towards the end of the device such that 10M will not be able to be accumulated from that point.
 dd if=/tmp/"$0_tmp_file" oflag=direct bs=10M seek=$progress of=$1
 if [[ $(dd if=/tmp/"$0_tmp_file" bs=$remainder_size  count=1 | sha1sum | cut -d ' ' -f1) = $(dd if=$1 iflag=direct skip=$progress bs=10M | sha1sum | cut -d ' ' -f1) ]]
 then
  echo "Last $remainder_size bytes OK"
 else
  echo "Checksum at last $remainder_size bytes failed"
 fi
fi