Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- set -e
- shopt -s lastpipe extglob
- set -o pipefail
- die() {
- echo "$@" >&2
- exit 1
- }
- [[ $# -ge 1 && $# -le 2 ]] || die "Usage: ${BASH_SOURCE} source.img [destination.img]"
- image="$1"
- [[ -f "$image" ]] || die "File not found: $image"
- if [[ $# -ge 2 ]]; then
- newimage="$2"
- else
- # remove suffix indicating image size
- if [[ "$image" == *-[1-9]gb.img ]]; then
- newimage="${image%-[1-9]gb.img}.img"
- else
- newimage="$image"
- fi
- fi
- [[ "$newimage" == "$image" || ! -f "$newimage" ]] || die "File exists: $newimage"
- # determine start of rootfs partition
- /sbin/sfdisk --dump /dev/stdin <"$image" | tail -n 1 | {
- read -rd,
- [[ "$REPLY" == '/dev/stdin1 : start='* ]] \
- || die "Not a single-partition image"
- start="${REPLY##*=}"
- (( start % 8 == 0 )) || die "Invalid partition start: $start"
- start=$(( start / 2 ))K
- }
- # rename image if requested
- if [[ "$newimage" != "$image" ]]; then
- mv "$image" "$newimage"
- image="$newimage"
- fi
- # split off the part before the rootfs partition (partition table, bootloader)
- head -c $start "$image" >"$image.header"
- fallocate -c -l $start "$image"
- # shrink filesystem to minimum size
- /sbin/e2fsck -f -p "$image" || [[ $? == 1 ]]
- /sbin/resize2fs -M "$image"
- # determine size of filesystem
- declare -A info
- /sbin/dumpe2fs -h "$image" 2>/dev/null | grep -P ': *\d+$' | \
- while IFS=: read -r k v; do
- info["${k// /_}"]="${v##*( )}"
- done
- size=$(( ${info[Block_size]:?} * ${info[Block_count]:?} / 1024 ))K
- # truncate image file to filesystem size
- truncate --no-create --size=$size "$image"
- # reinsert the stuff before the rootfs partition (partition table, bootloader)
- fallocate -i -l $start "$image"
- cat "$image.header" 1<>"$image"
- rm "$image.header"
- # update partition table to match new filesystem size
- echo ",$size" | /sbin/sfdisk -N 1 "$image"
- # all done! report image name and size
- echo "$image ($start + $size)"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement