Skip to content

Instantly share code, notes, and snippets.

@estevesd
Created August 21, 2019 12:36
Show Gist options
  • Save estevesd/e8d957c736599a1aef2d16f884d03ffe to your computer and use it in GitHub Desktop.
Save estevesd/e8d957c736599a1aef2d16f884d03ffe to your computer and use it in GitHub Desktop.
Mount and manage image files on Linux
#!/bin/bash
IMG=$1
if [ -z "$IMG" ];then
echo no image file selected
exit 1
fi
if echo "$IMG" | grep " " &>/dev/null;then
echo "Remove spaces in file name"
exit 1
fi
if [ "$(id -u)" != "0" ]; then
echo "This command must be run as root" 1>&2
exit 1
fi
PARTITIONS=$(kpartx -l "$IMG" | grep -v "loop deleted")
if [ -z "$PARTITIONS" ];then
echo "no partitions available to mount"
exit 1
fi
FRIENDLY_PARTITIONS_LIST=$(fdisk -l "$IMG" | grep "^$IMG" | awk '{printf "%-10s %s\n", $6,$5}' | awk '{print NR" - "$0}')
LOOPS=$(echo "$PARTITIONS" | awk '{print $1}')
echo "Partitions detected :"
echo "$FRIENDLY_PARTITIONS_LIST"
echo -n "Which partition do you want to mount ? "
read SELECTED_PARTITION
LOOP=$(echo "$LOOPS" | sed "${SELECTED_PARTITION}q;d")
IMG_NAME=$(basename $IMG)
IMG_NAME=${IMG_NAME%.*}
mkdir -p "/mnt/${IMG_NAME}"
kpartx -a "$IMG"
if [ -e /dev/mapper/$LOOP ] && [ -e "/mnt/${IMG_NAME}" ];then
if mount /dev/mapper/$LOOP /mnt/${IMG_NAME};then
echo "Your image is mounted in /mnt/$IMG_NAME"
echo "$IMG /mnt/$IMG_NAME /dev/mapper/$LOOP" >> ~/.mounted_images
exit 0
else
echo "Unable to mount $IMG_NAME"
exit 1
fi
else
echo "Unable to create the loop for $IMG_NAME or mount directory doesn't exist"
exit 1
fi
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "This command must be run as root" 1>&2
exit 1
fi
MOUNTED_IMAGES=$(cat ~/.mounted_images)
if [ -z "$MOUNTED_IMAGES" ];then
echo "No images were mounted with this tool"
exit 0
fi
FRIENDLY_IMAGES_LIST=$(echo "$MOUNTED_IMAGES" | awk '{print NR" - "$1}')
echo "$FRIENDLY_IMAGES_LIST"
echo -n "Which image do you want to unmount ? "
read -r SELECTED_IMG
SELECTED_IMG=$(echo "$MOUNTED_IMAGES" | sed "${SELECTED_IMG}q;d")
IMAGE_FILE=$(echo "$SELECTED_IMG" | awk '{print $1}')
MOUNT_PATH=$(echo "$SELECTED_IMG" | awk '{print $2}')
if umount $MOUNT_PATH &> /dev/null;then
echo "Image succesfully unmounted"
else
echo "Unable to unmount this image"
exit 1
fi
if rm -r $MOUNT_PATH &> /dev/null ;then
echo "Mount directory removed"
else
echo "Unable to remove mount directory"
exit 1
fi
if kpartx -d $IMAGE_FILE &> /dev/null;then
echo "Loop deleted"
else
echo "Unable to remove $(echo "$SELECTED_IMG" | awk '{print $3}')"
exit 1
fi
if sed -i "\|$IMAGE_FILE|d" ~/.mounted_images;then
echo "Cleanup done"
exit 0
else
echo "Cleanup failed. ~/.mount_images may contain wrong informations"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment