Created
September 10, 2014 02:19
-
-
Save Pesticles/d16ad533a09927362a80 to your computer and use it in GitHub Desktop.
SD Card image shrinker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
IMG="$1" | |
if [[ -e $IMG ]]; then | |
P_START=$( fdisk -lu $IMG | grep Linux | awk '{print $2}' ) # Start of 2nd partition in 512 byte sectors | |
P_SIZE=$(( $( fdisk -lu $IMG | grep Linux | awk '{print $3}' ) * 1024 )) # Partition size in bytes | |
losetup /dev/loop2 $IMG -o $(($P_START * 512)) --sizelimit $P_SIZE | |
fsck -f /dev/loop2 | |
resize2fs -M /dev/loop2 # Make the filesystem as small as possible | |
fsck -f /dev/loop2 | |
P_NEWSIZE=$( dumpe2fs /dev/loop2 2>/dev/null | grep '^Block count:' | awk '{print $3}' ) # In 4k blocks | |
P_NEWEND=$(( $P_START + ($P_NEWSIZE * 8) + 1 )) # in 512 byte sectors | |
losetup -d /dev/loop2 | |
echo -e "p\nd\n2\nn\np\n2\n$P_START\n$P_NEWEND\np\nW\n" | fdisk $IMG | |
I_SIZE=$((($P_NEWEND + 1) * 512)) # New image size in bytes | |
truncate -s $I_SIZE $IMG | |
else | |
echo "Usage: $0 filename" | |
fi |
This just saved me TON OF headache, i'm so thankful i found this. i have been looking for a similar solution for days. i can't just thank enough
fdisk didn't like the capital W
for me.
$ fdisk --version
fdisk from util-linux 2.28.2
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exactly what I have been looking for! But I've never run bash before. How do I execute this from my Pi? Thanks a ton.