#!/bin/bash #write a file to /dev/mmcblk0 making sure it is unmounted first. #Functions: #Unmount all partitions on the device unmount_partitions() { RET=0 for i in $(grep $1 /proc/mounts | awk '{print $1}') do echo unmounting $i >&2 sudo umount $i if [ $? -ne 0 ]; then RET=$? echo Failed to unmount $i >&2 fi done return $RET } #Write the image to the SD card calling xzcat or zcat, or just plain cat #as needed. write_image() { FILE=$1 DEVICE=$2 case $(file -b $FILE | awk -F, '{print $1}') in compress*) echo "old style UNIX compress(1) format detected" >&2; CAT=zcat;; gzip*) echo "gzip detected" >&2; CAT=zcat;; XZ*) echo "XZ detected" >&2; CAT=xzcat;; bzip2*) echo "bzip2 detected" >&2; CAT=bzcat;; *) echo "uncompressed or unsupported compression methods detected using cat" >&2; CAT=cat;; esac echo -n Calculating image size: >&2 SIZE=$($CAT $FILE | wc -c) echo "$SIZE bytes" >&2 $CAT $FILE | pv -pterb -s $SIZE | sudo dd of=$DEVICE } #Main if [ "x$2" = "x" ]; then DEVICE=/dev/mmcblk0 else DEVICE="$2" fi if [ -b $DEVICE ]; then if [ ! -f $1 ]; then echo cannot open $1! >&2 exit 1 fi unmount_partitions $DEVICE if [ $? -ne 0 ]; then echo "Couldn't unmount all partitions on $DEVICE" >&2 exit 1 fi echo -n "Are you sure you want to erase $DEVICE and write $1? (y/n):" >&2 read yn if [ "x$yn" = "xy" ];then echo "writing to $DEVICE in 5 seconds" >&2 sleep 5 else echo "ABORTING!" >&2 exit 1 fi which blkdiscard >/dev/null if [ $? -eq 0 ]; then sudo blkdiscard -v $DEVICE fi write_image $1 $DEVICE if [ $? -ne 0 ]; then echo "Something went wrong write_image returned $?" >&2 exit 1 else echo "Image was written successfully" sync fi else echo block device $DEVICE does not exist! >&2 exit 1 fi