Skip to content

Instantly share code, notes, and snippets.

@jlinoff
Created March 18, 2016 21:19
Show Gist options
  • Save jlinoff/632157524d784bb957de to your computer and use it in GitHub Desktop.
Save jlinoff/632157524d784bb957de to your computer and use it in GitHub Desktop.
Bash script to automatically find and fix the partitions in an image file on linux using losetup, fdisk, mke2fs and fsck.
#!/bin/bash
#
# This image will fix all of the partitions in a disk image.
#
# Usage:
# fix-image.sh test.img
#
# License: MIT Open Source
# Copyright (c) 2016 by Joe Linoff
# ================================================================
# Main
# ================================================================
ImgFile="$1"
echo "INFO: ImgFile=$ImgFile"
if (( ${#ImgFile} == 0 )) ; then
echo "ERROR: Must specify an image file."
exit 1
fi
if [ ! -f "$ImgFile" ] ; then
echo "ERROR: File does not exist: $ImgFile."
exit 1
fi
# Try to fix all of the partitions.
# Find them using fdisk -l.
Offsets=($(fdisk -l test.img | egrep -A 10 'Device[ ]+Boot[ ]+Start' | tail -n +2 | awk '{print $3}'))
for Offset in ${Offsets[@]} ; do
(( Offset = 512 * Offset ))
echo "INFO: Offset=$Offset"
LoopDevice=$(losetup -f)
echo "INFO: LoopDevice=$LoopDevice"
set -x
sudo losetup -o $Offset $LoopDevice $ImgFile
{ set +x ; } 2>/dev/null
echo "INFO: File system information"
set -x
sudo mke2fs -n $LoopDevice
{ set +x ; } 2>/dev/null
echo "INFO: Fix file system"
set -x
sudo fsck -f -p -D $LoopDevice
st=$?
{ set +x ; } 2>/dev/null
echo -n "INFO: Status=$st "
case $st in
0)
echo "No errors"
;;
1)
echo "File system errors corrected"
;;
2)
echo "File system errors corrected, system should be rebooted"
;;
4)
echo "File system errors left uncorrected"
;;
8)
echo "Operational error"
;;
16)
echo "Usage or syntax error"
;;
32)
echo "Canceled by user request"
;;
128)
echo "Shared library error"
;;
*)
echo "Uknown error"
;;
esac
set -x
sudo losetup -d $LoopDevice
{ set +x ; } 2>/dev/null
done
echo "INFO: Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment