Skip to content

Instantly share code, notes, and snippets.

Created April 21, 2023 20:32
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
From 49.4 MB to 13.8 MB of a compressed µlfs hdd.img
#!/bin/bash -eu
# µlfs runtime module minimization
# Check (due to bash -e)
which zerofree
# Mount the image
LOOP="$(sudo losetup --partscan --show --find $IMG)"
mkdir -p mnt/
sudo mount $PART mnt/
# Drop the script
echo '#!/bin/sh
# Get used modules
USED="$(cat /proc/modules | cut -d" " -f1 | xargs modinfo | grep filename)"
USED="$(echo "$USED" | rev | cut -d" " -f1 | rev)"
echo "$USED" | sort > /root/used.txt
# Get all modules
ALL="$(find /lib/modules -type f -name "*.ko.gz")"
echo "$ALL" | sort > /root/all.txt
# Substract
SUB="$(comm -3 /root/all.txt /root/used.txt)"
# Remove from root
echo "$SUB" | xargs rm -f
find /lib/modules -type d -empty -delete
# Now for the initramfs, extract
gzip -d /boot/initramfs.cpio.gz
mkdir /root/initramfs
cd /root/initramfs
cpio -idm -F /boot/initramfs.cpio
rm /boot/initramfs.cpio
# Clean
echo "$SUB" | while read line; do echo "/root/initramfs/$line"; done | \
tail -n+2 | xargs rm -f
find ./lib/modules -type d -empty -delete
# Pack again
find . -print0 | cpio -o -H newc -0 | gzip --best > /boot/initramfs.cpio.gz
# Cleanup
rm -rf /root/all.txt /root/used.txt /root/initramfs $0
' | sudo tee mnt/$DROPPED
sudo chmod +x mnt/$DROPPED
# Unmount
sudo umount mnt/
sudo losetup -d $LOOP
# Wait
echo -e "\nScript dropped at $DROPPED"
echo "Please boot the disk and execute it"
echo "Then, power off and hit enter, or Ctrl-C to abort"
# Mount the loop device again
LOOP="$(sudo losetup --partscan --show --find $IMG)"
# Zerofree
sudo zerofree $PART
# Unmount the loop device
sudo losetup -d $LOOP
# That's it! Compress with something in the lines of:
# xz -k -T`nproc` -v hdd.img
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment