#!/bin/sh set -e die() { echo "$(basename "$0"): $1" && exit 1 ; } # file check ! [ "$1" ] && die "No file was specified" ! [ -f "$1" ] && die "$1 is not a file" # mountpoint check ! [ "$2" ] && die "No mountpoint was specified" ! [ -d "$2" ] && die "Mountpoint $2 is not a directory" [ "`ls -A "$2"`" ] && die "Mountpoint $2 is not empty" # check disk image validity ! fdisk -lu "$1" 2>&1 | grep -m1 "\s*Start\s*End" >/dev/null && die "File $1 is not a disk image" # get sectorsize #sectorsize=$(fdisk -lu "$1" | grep -m1 '^Units:' | cut -d' ' -f8) # Sector size is 8th word sectorsize=512 # get partition num, if there is more than one part, interactively if not available # TODO check if there is no partitions partition="$3" if [ -z "$partition" ]; then fdisk -o Size,Type,Name -lu "$1" | awk '!f{print $0};f>0{print " " f-1 ") " $0; f++};f==-1{print "Part " $0;f=1};/^$/{f=-1}' printf "\nChoose partition number to mount: " read partition fi # check if part num valid [ -z "${partition##*[!0-9]*}" ] && die "Illegal number: '$partition'" # get offset from fdisk fdisk_ignore_lines=9 # ignore first 9 lines of output offset=$(fdisk -o Start -l "$1" | sed $(( fdisk_ignore_lines + partition ))'q;d' ) # check if that produced a valid offset [ -z "$offset" ] && die "Partition $partition does not exist" # try to mount mount -o loop,offset=$(( offset * sectorsize )) "$1" "$2" && echo "Successfully mounted" || die "Error mounting"