Last active
October 10, 2017 20:36
-
-
Save xenithorb/33499acdba719c7f547561f0faaa29ee to your computer and use it in GitHub Desktop.
A bash script to quickly unmount my layered external block device
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
#!/bin/bash | |
# A script to quickly unmount an external USB drive I have that I am using | |
# multiple block device layers with, like bcache, lvm, luks, etc. | |
# Assumptions here are that the aforementioned relevant crypttab and fstab | |
# entries are present. If they are, systemd should take care of the rest. | |
# If it works correctly, the last thing the mounting command should do is | |
# ask you for the unlocking password. | |
# | |
# Author: Michael Goodwin | |
# Date: 2017-10-10 | |
# | |
BTRFS_LUKS=/dev/mapper/luks-btrfs_backup | |
BCACHE_DEV=bcache0 | |
LVM_VG=ext1 | |
SCRIPT_NAME=$0 | |
__usage() { | |
cat <<-EOF | |
Usage: | |
- Unmount: $SCRIPT_NAME -u | |
- Mount: $SCRIPT_NAME -m | |
EOF | |
} | |
__umount() { | |
sudo -s \ | |
LVM_VG="${LVM_VG}" \ | |
BTRFS_LUKS="${BTRFS_LUKS}" \ | |
BCACHE_DEV="${BCACHE_DEV}" \ | |
<<-'EOF' | |
mountpoint -qx "${BTRFS_LUKS}" >/dev/null 2>&1 || { echo "Not mounted!"; exit 1; } | |
umount -l "${BTRFS_LUKS}" \ | |
&& cryptsetup close "${BTRFS_LUKS}" \ | |
&& vgchange -an "${LVM_VG}" \ | |
&& echo 1 > "/sys/block/${BCACHE_DEV}/bcache/stop" | |
EOF | |
} | |
__mount() { | |
# In this instance, simply activating the bcache devices | |
# triggers systemd/udev to do everything else, we just | |
# need to supply the password to cryptsetup through tty-ask-password | |
sudo BCACHE_DEV="${BCACHE_DEV}" -s <<-'EOF' | |
readarray -t devs < <(find /dev -type b -name "sd*") | |
for ((i=0;i<${#devs[@]};i++)); do | |
echo "${devs[i]}" > "/sys/fs/bcache/register_quiet" | |
done | |
sleep 2 | |
systemd-tty-ask-password-agent --query | |
EOF | |
} | |
while getopts "hum" opt; do | |
case $opt in | |
m) __mount ;; | |
u) __umount ;; | |
*) __usage ;; | |
esac | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment