Skip to content

Instantly share code, notes, and snippets.

@ljfranklin
Last active December 18, 2017 00:10
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 ljfranklin/629689166673cc71a5f5d256738bec7b to your computer and use it in GitHub Desktop.
Save ljfranklin/629689166673cc71a5f5d256738bec7b to your computer and use it in GitHub Desktop.
Script for OSX and Linux to add an SSH key and eject the disk
#!/usr/bin/env bash
set -e
HOURS=$1
green='\033[32m'
yellow='\033[33m'
nc='\033[0m'
if [ -z $HOURS ] || [ "$HOURS" == '-h' ] || [ "$HOURS" == '--help' ]; then
echo -e "${yellow}Adds your SSH Key for the given number of hours and ejects the USB drive${nc}"
echo -e "${yellow}Usage: $0 <num hours>${nc}"
exit 1
fi
echo -e "${green}> Adding SSH Key...${nc}"
ssh-add -t ${HOURS}H $(dirname $0)/id_rsa
echo -e "${green}> Ejecting USB drive...${nc}"
mountpoint="$(dirname $0)"
if [ "$(uname)" == "Darwin" ]; then
diskutil umount force "${mountpoint}"
echo -e "${green}> Done!${nc}"
else
# TODO: is there a way to safely eject given the mountpoint?
device_name="$(lsblk --json | jq -r --arg mountpoint "${mountpoint}" '.blockdevices[] | . as $parent | .. | .mountpoint? | select(. == $mountpoint) | $parent.name')"
partition_name="$(lsblk --json | jq -r --arg mountpoint "${mountpoint}" --arg device_name "${device_name}" '.blockdevices[] | select(.name == $device_name) | .children[] | . as $partition | .. | .mountpoint? | select(. == $mountpoint) | $partition.name')"
# replace the current process so Linux doesn't see the drive as "in use"
exec bash <<EOF
cd $HOME && \
umount "${mountpoint}" && \
udisksctl lock -b "/dev/${partition_name}" > /dev/null && \
udisksctl power-off -b "/dev/${device_name}" && \
echo -e "${green}> Done!${nc}"
EOF
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment