Created
July 23, 2025 15:13
-
-
Save 84adam/2b48cde67125bd83b237d694d54e7f40 to your computer and use it in GitHub Desktop.
bash script to help unlock/mount/unmount LUKS encrypted drive
This file contains hidden or 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 | |
# Unified LUKS Drive Management Script | |
DEVICE="/dev/sdb1" # Update to your encrypted partition | |
MAPPER_NAME="myluksdrive" # Must match name used during setup | |
MOUNT_POINT="/mnt/encrypted" # Update mount path if needed | |
if [ "$#" -ne 1 ]; then | |
echo "Usage: $0 [mount|unmount]" | |
exit 1 | |
fi | |
case "$1" in | |
mount) | |
# Check if device exists | |
if [ ! -b "$DEVICE" ]; then | |
echo "Error: Device $DEVICE not found!" >&2 | |
echo "Use 'lsblk' to find your device and update DEVICE variable" >&2 | |
exit 1 | |
fi | |
# Check if already mounted | |
if grep -qs "/dev/mapper/$MAPPER_NAME" /proc/mounts; then | |
echo "Error: Drive is already mounted" >&2 | |
exit 1 | |
fi | |
# Unlock drive | |
echo "Unlocking $DEVICE..." | |
if ! sudo cryptsetup open "$DEVICE" "$MAPPER_NAME"; then | |
echo "Error: Failed to unlock device!" >&2 | |
exit 1 | |
fi | |
# Mount drive | |
echo "Mounting to $MOUNT_POINT..." | |
sudo mkdir -p "$MOUNT_POINT" | |
if sudo mount "/dev/mapper/$MAPPER_NAME" "$MOUNT_POINT"; then | |
echo "Successfully mounted at $MOUNT_POINT" | |
else | |
echo "Error: Mounting failed!" >&2 | |
sudo cryptsetup close "$MAPPER_NAME" | |
exit 1 | |
fi | |
;; | |
unmount) | |
# Check if mounted | |
if ! grep -qs "/dev/mapper/$MAPPER_NAME" /proc/mounts; then | |
echo "Error: Drive is not currently mounted at $MOUNT_POINT" >&2 | |
exit 1 | |
fi | |
# Unmount drive | |
if sudo umount "$MOUNT_POINT"; then | |
echo "Unmounted $MOUNT_POINT" | |
sudo cryptsetup close "$MAPPER_NAME" | |
echo "Drive locked" | |
else | |
echo "Error: Failed to unmount! (Is something using the drive?)" >&2 | |
exit 1 | |
fi | |
;; | |
*) | |
echo "Invalid argument: $1" >&2 | |
echo "Usage: $0 [mount|unmount]" >&2 | |
exit 1 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment