#!/bin/sh die() { printf "%s: Error: %s\n" "$0" "$*" >&2; exit 1; } [ "$(id -u)" = 0 ] || die 'you are not root' shrink() { local shrinkmegs=100 mountpoint="$1" while true; do while ! btrfs filesystem resize -${shrinkmegs}M "$mountpoint"/; do shrinkmegs=$((shrinkmegs - 10 )) if [ $shrinkmegs -lt 10 ]; then return fi done done } btrfs_truncate() { local img="$1" bytes # 548044800/1176715264 bytes used bytes=$(file "$img" | sed -ne 's?.*/\([0-9]*\) bytes used.*?\1?p') if [ "$bytes" ]; then truncate -s "$bytes" "$img" fi } main() { if [ -d "$1" ]; then mountpoint=$1 mountpoint -q "$mountpoint" || die "not a mountpoint: $1" shrink "$mountpoint" elif [ -f "$1" ]; then mountpoint="$1".mnt.tmp mkdir "$mountpoint" mount -t btrfs "$1" "$mountpoint" result=$? if [ $result = 0 ]; then shrink "$mountpoint" result=$? umount "$mountpoint" fi rmdir "$mountpoint" btrfs_truncate "$1" return $result else die "not a file or directory: $1" fi } main "$@"