Skip to content

Instantly share code, notes, and snippets.

@alekratz
Created July 15, 2015 18:21
Show Gist options
  • Save alekratz/e1af0c832d5f05613415 to your computer and use it in GitHub Desktop.
Save alekratz/e1af0c832d5f05613415 to your computer and use it in GitHub Desktop.
automatic image resizer
#!/bin/bash
# Automatic Image file resizer
# Written by SirLagz
# Fixed and cleaned by Alek Ratzloff <alekratz@gmail.com>
if [[ ! $(whoami) =~ "root" ]]; then
echo ""
echo "**********************************"
echo "*** This should be run as root ***"
echo "**********************************"
echo ""
exit
fi
if [[ -z $1 ]]; then
echo "Usage: $0 image.img"
exit
fi
if [[ ! -e $1 || ! $(file $1) =~ "x86" ]]; then
echo "Error : Not an image file, or file doesn't exist"
exit
fi
partinfo=$(parted -m $1 unit B print)
partnumber=$(echo "$partinfo" | grep ext4 | awk -F: ' { print $1 } ')
partstart=$(echo "$partinfo" | grep ext4 | awk -F: ' { print substr($2,0,length($2)) } ')
loopback=$(losetup -f --show -o $partstart $1)
e2fsck -f $loopback
minsize=$(resize2fs -P $loopback | awk -F': ' ' { print $2 } ')
minsize=$(echo $minsize+1000 | bc)
resize2fs -p $loopback $minsize
sleep 1
losetup -d $loopback
partnewsize=$(echo "$minsize * 4096" | bc)
newpartend=$(echo "$partstart + $partnewsize" | bc)
part1=$(parted $1 rm $partnumber)
part2=$(parted $1 unit B mkpart primary $partstart $newpartend)
endresult=$(parted -m $1 unit B print free | tail -1 | awk -F: ' { print substr($2,0,length($2)-1) } ')
truncate -s $endresult $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment