mirror of
https://github.com/lisanet/PiShrink-macOS.git
synced 2026-02-18 02:55:52 +00:00
85 lines
2.3 KiB
Bash
Executable File
85 lines
2.3 KiB
Bash
Executable File
#!/bin/zsh
|
|
|
|
usage() { echo "Usage: $0 imagefile.img [newimagefile.img]"; exit 1; }
|
|
|
|
cleanup() {
|
|
[[ -n "$loopback" ]] && hdiutil detach "$loopback" >/dev/null 2>&1
|
|
}
|
|
trap cleanup EXIT
|
|
|
|
#Args
|
|
img="$1"
|
|
|
|
#Usage checks
|
|
[ -z "$img" ] && usage
|
|
[ ! -f "$img" ] && { echo "ERROR: $img is not a file..."; exit 2; }
|
|
|
|
#Check that what we need is installed
|
|
for command in tune2fs e2fsck resize2fs; do
|
|
command -v $command 2>&1 >/dev/null
|
|
[ $? -ne 0 ] && { echo "ERROR: $command is not installed."; exit 4; }
|
|
done
|
|
|
|
#Copy to new file if requested
|
|
if [ -n "$2" ]; then
|
|
echo "Copying $1 to $2..."
|
|
cp "$1" "$2"
|
|
[ $? -ne 0 ] && { echo "ERROR: Could not copy file..."; exit 5; }
|
|
img="$2"
|
|
fi
|
|
|
|
#Gather info
|
|
beforesize=$(ls -lh "$img" | awk '{print $5}')
|
|
partnum=$(fdisk "$img" | tr -d ":" | awk '$2=="83" {print $1}')
|
|
partstart=$(fdisk -d "$img" | awk -F "," '/0x83/ {print $1}')
|
|
loopback=$(hdiutil attach -nomount "$img" | awk '/Linux/ {print $1}')
|
|
tune2fs_output=$(tune2fs -l "$loopback")
|
|
currentsize=$(echo "$tune2fs_output" | awk '/Block count:/ {print $NF}')
|
|
blocksize=$(echo "$tune2fs_output" | awk '/Block size:/ {print $NF}')
|
|
|
|
#Make sure filesystem is ok, force yes on all questions
|
|
echo "Checking filesystem on partition $partnum ..."
|
|
e2fsck -y -f "$loopback"
|
|
minsize=$(resize2fs -P "$loopback" | awk -F ': ' '{print $2}')
|
|
|
|
# add 200 MB of extra space, the system may need it to run, minsize is in blocks unit
|
|
minsize=$(($minsize + 200 * 1048576 / $blocksize))
|
|
|
|
[ $minsize -gt $currentsize ] && { echo "ERROR: Image already shrunk to smallest size"; exit 3; }
|
|
|
|
#Shrink filesystem
|
|
echo
|
|
echo "Shrinking partition $partnum starting at block $partstart on $img..."
|
|
resize2fs -p "$loopback" $minsize
|
|
[ $? -ne 0 ] && { echo "ERROR: resize2fs failed..."; exit 7; }
|
|
sleep 1
|
|
|
|
#Shrink partition
|
|
hdiutil detach $loopback
|
|
# fdisk uses a block size of 512 Bytes!
|
|
partnewsize=$(($minsize * $blocksize / 512))
|
|
newpartend=$(($partstart + $partnewsize))
|
|
|
|
# now use fdisk to change the partition
|
|
echo
|
|
echo "Updating partition table to new size ..."
|
|
fdisk -e "$img" 2>/dev/null <<EOF2
|
|
e $partnum
|
|
|
|
|
|
|
|
$newpartend
|
|
w
|
|
q
|
|
|
|
EOF2
|
|
sleep 1
|
|
|
|
#Truncate the file
|
|
endresult=$(($newpartend * 512))
|
|
truncate -s $endresult "$img"
|
|
aftersize=$(ls -lh "$img" | awk '{print $5}')
|
|
echo
|
|
echo
|
|
echo "Shrunk $img from $beforesize to $aftersize"
|