Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mount a Raspberry Pi image of your choice :)
#!/bin/bash
# Globals
TIMESTAMP=$(date +%s)
MOUNT_DIR="/mnt"
BASE_MOUNT_DIR="$MOUNT_DIR/image_$TIMESTAMP"
MOUNT_IMAGE=""
# Usage declaration
display_usage() {
cat << EOF
Usage: sudo $0 [options]
[required]
-i /path/to/image Path to the disk image to be mounted/modified
[optional]
-f my_folder_name Folder to mount the specified image (via the -i flag) at within the $MOUNT_DIR directory
[extra]
-h Brings up this help screen
EOF
exit $1
}
# Error message handler
error() {
printf "\n Error: $1\n"
display_usage 1
}
# Check the script is running as root
if [[ $EUID -ne 0 ]]; then
error "Please check that the script is running as root"
fi
# Check, process and validate parameters
while getopts "f:hi:" flag; do
case "${flag}" in
f)
# Validate that the mount directory doesn't already exist
BASE_MOUNT_DIR="$MOUNT_DIR/${OPTARG}"
if [ -d "$BASE_MOUNT_DIR" ]; then
error "$BASE_MOUNT_DIR already exists"
fi
;;
h)
# Display help...
display_usage 0
;;
i)
# Validate that the image is indeed a valid file
MOUNT_IMAGE="${OPTARG}"
if [ ! -f "$MOUNT_IMAGE" ]; then
error "$MOUNT_IMAGE is not a valid file"
fi
;;
*)
# What happened!
display_usage 0
;;
esac
done
# Set the mount directories
BOOT_MOUNT_DIR="$BASE_MOUNT_DIR/boot"
ROOT_MOUNT_DIR="$BASE_MOUNT_DIR/root"
echo 'Capturing partition details...'
BOOT_PARTITION=`fdisk -l "$MOUNT_IMAGE" | grep "c W95 FAT32 (LBA)"`
ROOT_PARTITION=`fdisk -l "$MOUNT_IMAGE" | grep "83 Linux"`
echo 'Capturing sector size...'
SECTOR_SIZE=`fdisk -l "$MOUNT_IMAGE" | grep "Sector size" | awk '{print $7}'`
echo 'Getting the starting sector of the partitions...'
BOOT_START_SECTOR=`echo "$BOOT_PARTITION" | awk '{print $2}'`
ROOT_START_SECTOR=`echo "$ROOT_PARTITION" | awk '{print $2}'`
echo 'Calculating the starting byte of the partitions...'
((BOOT_START_BYTE=$BOOT_START_SECTOR * $SECTOR_SIZE))
((ROOT_START_BYTE=$ROOT_START_SECTOR * $SECTOR_SIZE))
echo 'Getting the sector length of the partitions...'
BOOT_SECTOR_LENGTH=`echo "$BOOT_PARTITION" | awk '{print $4}'`
ROOT_SECTOR_LENGTH=`echo "$ROOT_PARTITION" | awk '{print $4}'`
echo 'Calculating the byte length of the partitions...'
((BOOT_BYTE_LENGTH=$BOOT_SECTOR_LENGTH * $SECTOR_SIZE))
((ROOT_BYTE_LENGTH=$ROOT_SECTOR_LENGTH * $SECTOR_SIZE))
echo 'Creating mount directories...'
sudo mkdir -p "$BOOT_MOUNT_DIR"
sudo mkdir -p "$ROOT_MOUNT_DIR"
echo 'Mounting partitions...'
mount -v -o offset=$BOOT_START_BYTE,sizelimit=$BOOT_BYTE_LENGTH -t vfat "$MOUNT_IMAGE" "$BOOT_MOUNT_DIR"
mount -v -o offset=$ROOT_START_BYTE,sizelimit=$ROOT_BYTE_LENGTH -t ext4 "$MOUNT_IMAGE" "$ROOT_MOUNT_DIR"
# Done!
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.