#!/bin/sh # set -x # # Write image to disk. # USAGE : ./prepare-disk /path/to/image.img # function accept { echo read -p "▶ $1 (yN) " -n 1 -r echo echo if [[ $REPLY =~ ^[Yy]$ ]] then return 0 fi return 1 } function log { echo " $1" } function write { DISK=$1 log "☕ Writing $IMAGE to disk - press Ctrl+T to see progress" CMD="sudo dd if=$IMAGE of=$DISK bs=8m" echo `eval $CMD` } function unmount { DISK=$1 log "🔨 Unmount $DISK" diskutil unmountDisk $DISK } function launch { DISK=$1 if accept " ⚠ Reformat $DISK with $IMAGE ?" then log "🚀 Launch operations on $DISK" unmount $DISK write $DISK unmount $DISK log "👌 Done !" fi } function listDevices { diskutil list | grep /dev/disk -A 2 | grep "0:" } function getDiskBySize { echo `eval "diskutil list | grep '*$1' | grep -oE \"[^ ]+\$\""` } function guessDevice { DEVICE=$(getDiskBySize "4.0 GB") if [[ ! $DEVICE ]] then DEVICE=$(getDiskBySize "8.0 GB") fi if [[ ! $DEVICE ]] then DEVICE=$(getDiskBySize "7.9 GB") fi if [[ ! $DEVICE ]] then DEVICE=$(getDiskBySize "7.7 GB") fi if [[ ! $DEVICE ]] then DEVICE=$(getDiskBySize "2.0 GB") fi if [[ $DEVICE ]] then # add /dev/r for raw access DEVICE="/dev/r$DEVICE" fi echo $DEVICE } IMAGE=$1 if [[ ! $IMAGE ]] then echo 'USAGE: prepare-disk /path/to/image.img' exit 1 fi listDevices log "Guess device..." DEVICE=$(guessDevice) if [[ ! $DEVICE ]] then echo '😡 No disk detected, use prepare-disk.sh /dev/XXX' echo '😡 Use diskutil list to check the device' exit 1 else launch $DEVICE fi