Last active
December 18, 2017 00:10
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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