Skip to content

Instantly share code, notes, and snippets.

@ayufan
Last active September 5, 2016 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayufan/ef261cd6a574ab607ea242d2383e6479 to your computer and use it in GitHub Desktop.
Save ayufan/ef261cd6a574ab607ea242d2383e6479 to your computer and use it in GitHub Desktop.
Simple script to write to sdcard on OSX
#!/bin/bash
# (c) 2016 Kamil Trzciński <ayufan@ayufan.eu>
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
stderr() {
echo "$@" 1>&2
}
if [[ $# -ne 1 ]] && [[ $# -ne 2 ]]; then
stderr "Usage: $0 <file> [disk]"
exit 1
fi
FILE="$1"
set -eo pipefail
if [[ ! -e "$FILE" ]]; then
stderr "File $FILE doesn't exist"
exit 1
fi
is_external() {
diskutil info $1 | grep -q "\(USB\|Secure Digital\)"
}
devices() {
diskutil list | grep "^/dev/" | awk '{print $1}'
}
uncompress_file() {
case "$(basename "$FILE")" in
*.gz)
stderr "Uncompressing $FILE to $SELECTED_DISK..."
gunzip -c
;;
*.xz)
stderr "Uncompressing $FILE to $SELECTED_DISK..."
unxz -c
;;
*)
stderr "Copying $FILE to $SELECTED_DISK..."
cat
;;
esac
}
SELECTED_DISK=""
for device in $(devices); do
# Just in case!
if [[ "$device" == "/dev/disk0" ]]; then
continue
fi
if ! is_external "$device"; then
continue
fi
if [[ -n "$2" ]]; then
if [[ "$device" == "$2" ]]; then
SELECTED_DISK="$device"
fi
continue
fi
if [[ "$SELECTED_DISK" != "" ]]; then
stderr "Multiple disks found: $device"
exit 1
fi
SELECTED_DISK="$device"
done
if [[ -z "$SELECTED_DISK" ]]; then
stderr "No disk found."
exit 1
fi
stderr "Using: $device..."
if ! diskutil unmountDisk "$SELECTED_DISK"; then
stderr "Failed to unmount $SELECTED_DISK"
exit 1
fi
if pv "$FILE" | uncompress_file | sudo dd of="$SELECTED_DISK" bs=1m; then
stderr "Succeeded."
else
stderr "Failed."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment