Skip to content

Instantly share code, notes, and snippets.

@mattbornski
Created May 21, 2013 22:59
Show Gist options
  • Save mattbornski/5623952 to your computer and use it in GitHub Desktop.
Save mattbornski/5623952 to your computer and use it in GitHub Desktop.
Imaging a USB flash drive from a Mac (suitable for making a bootable Ubuntu flash drive, for instance).
#!/bin/bash
echo "Searching for available ISO..."
find ~ -name "*.iso" -type f -size +1048576 | xargs ls -l
read -e -p "Which ISO should be used? " ISO_FILE
if [ "${ISO_FILE}" == "" ] ; then
echo "No ISO selected!"
exit 1
fi
echo "Using ${ISO_FILE}"
ls ${ISO_FILE} 1>/dev/null 2>&1
EXISTENCE_CHECK=$?
if [ ! "${EXISTENCE_CHECK}" == "0" ] ; then
echo "ISO file does not exist: ${ISO_FILE}"
exit 1
fi
df -h
read -e -p "Which device should we image? " DEVICE
echo "Imaging ${DEVICE}"
ls ${DEVICE} 1>/dev/null 2>&1
EXISTENCE_CHECK=$?
if [ ! "${EXISTENCE_CHECK}" == "0" ] ; then
echo "Device does not exist: ${DEVICE}"
exit 1
fi
# Convert /dev/disk1s1 to /dev/disk1 (the "parent device name")
# And thence to /dev/rdisk1 (the "raw device name")
PARENT_DEVICE=$(dirname ${DEVICE})/$(basename ${DEVICE} | grep -oE "^[a-zA-Z]+[0-9]*" | head -1)
RAW_DEVICE=$(dirname ${PARENT_DEVICE})/r$(basename ${PARENT_DEVICE})
ls ${RAW_DEVICE} 1>/dev/null 2>&1
EXISTENCE_CHECK=$?
if [ ! "${EXISTENCE_CHECK}" == "0" ] ; then
echo "Raw device does not exist: ${RAW_DEVICE}"
exit 1
fi
# Convert the ISO to a disk image file
IMG_FILE=${ISO_FILE%.*}.img
if [ -e "${IMG_FILE}" ] ; then
echo "Disk image file already exists, not converting ISO"
else
echo "Converting ISO file to disk image file"
hdiutil convert -format UDRW -o ${IMG_FILE} ${ISO_FILE}
# Damn you implicit defaults
mv ${IMG_FILE}.dmg ${IMG_FILE}
fi
sudo diskutil unmountDisk ${PARENT_DEVICE}
if [ "$?" == "0" ] ; then
sudo dd bs=1m if=${IMG_FILE} of=${RAW_DEVICE}
# chug chug chug chug chugs
if [ "$?" == "0" ] ; then
# Done, now unmount so we can eject
diskutil eject ${PARENT_DEVICE}
if [ "$?" == "0" ] ; then
echo "Done"
exit 0
fi
fi
fi
echo "Writing ISO file to USB drive failed"
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment