Skip to content

Instantly share code, notes, and snippets.

@Kukunin
Forked from ba0f3/ubuntu-resize-rootfs.sh
Created June 21, 2025 04:36
Show Gist options
  • Save Kukunin/d522668a3226b269a2ed1f1dde2e8e32 to your computer and use it in GitHub Desktop.
Save Kukunin/d522668a3226b269a2ed1f1dde2e8e32 to your computer and use it in GitHub Desktop.
resize rootfs with out need of LiveCD (w/ or w/o LVM) - need to reboot once.
#!/bin/bash
#
# Resize root filesystem during boot.
#
# Alternative: http://www.ivarch.com/blogs/oss/2007/01/resize-a-live-root-fs-a-howto.shtml
# New size of root filesystem
ROOT_SIZE="100G"
# Check current filesystem type
ROOT_FS_TYPE="$(sed -n -e 's|^/dev/\S\+ / \(ext4\) .*$|\1|p' /proc/mounts)"
test "$ROOT_FS_TYPE" == ext4 || exit 100
# Copy e2fsck and resize2fs to initrd
cat > /etc/initramfs-tools/hooks/resize2fs <<"EOF"
#!/bin/sh
PREREQ=""
prereqs() {
echo "$PREREQ"
}
case "$1" in
prereqs)
prereqs
exit 0
;;
esac
. /usr/share/initramfs-tools/hook-functions
copy_exec /sbin/findfs /sbin
copy_exec /sbin/e2fsck /sbin
copy_exec /sbin/resize2fs /sbin
EOF
chmod +x /etc/initramfs-tools/hooks/resize2fs
# Execute resize2fs before mounting root filesystem
cat > /etc/initramfs-tools/scripts/local-premount/resize <<"EOF"
#!/bin/sh
PREREQ=""
prereqs() {
echo "$PREREQ"
}
case "$1" in
prereqs)
prereqs
exit 0
;;
esac
# Convert root from possible UUID to device name
echo "root=${ROOT} "
ROOT_DEVICE=""
for x in $(cat /proc/cmdline); do
case ${x} in
root=*)
value=${x#*=}
# Find the device node path depending on the form of root= :
case ${value} in
UUID=*)
ROOT_DEVICE=/dev/disk/by-uuid/${value#UUID=}
;;
LABEL=*)
ROOT_DEVICE=/dev/disk/by-label/${value#LABEL=}
;;
*)
ROOT_DEVICE=${value}
;;
esac
;;
esac
done
echo "root device name is ${ROOT_DEVICE} "
# Check root filesystem
/sbin/e2fsck -y -v -f "$ROOT_DEVICE" || echo "e2fsck: $? "
# Resize
# debug-flag 8 means debug moving the inode table
/sbin/resize2fs -d 8 "$ROOT_DEVICE" "$ROOT_SIZE" || echo "resize2fs: $? "
EOF
sed -i "s/\$ROOT_SIZE/$ROOT_SIZE/g" /etc/initramfs-tools/scripts/local-premount/resize
chmod +x /etc/initramfs-tools/scripts/local-premount/resize
# Regenerate initrd
update-initramfs -u
# Remove files
rm -f /etc/initramfs-tools/hooks/resize2fs /etc/initramfs-tools/scripts/local-premount/resize
reboot
# List files in initrd
# lsinitramfs /boot/initrd.img-*-amd64
# Remove files from initrd after reboot
# update-initramfs -u
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment