#!/bin/bash # ============ R e q u i r e s package guestfs-tools if [ "$(id -u)" -ne 0 ]; then echo "This script must be run as root." >&2 exit 1 fi # ------ Settings TmpDir=/localdisk/tmp # ------ Settings mkdir -p ${TmpDir} file=${1} out_file=${2} SparseFile="${out_file}.sparse" ShrunkFile="${out_file}.shrunk" echo "Compressing file ${file}..." Cmd="/usr/bin/virt-sparsify" Cmd="${Cmd} --check-tmpdir=continue" Cmd="${Cmd} --tmp=${TmpDir}" Cmd="${Cmd} -q" Cmd="${Cmd} ${file} ${SparseFile}" Cmd="${Cmd} && /usr/bin/qemu-img convert" Cmd="${Cmd} -c" Cmd="${Cmd} -O qcow2" Cmd="${Cmd} ${SparseFile} ${ShrunkFile}" echo ${Cmd} eval ${Cmd} if [ ${?} -ne 0 ] then echo "Compression failed. Removing ${ShrunkFile}" rm ${ShrunkFile} else filesz=$(stat -c %s ${file}) cfilesz=$(stat -c %s ${ShrunkFile}) ratio=$((cfilesz * 100 / filesz)) echo "Compression is successful. Compression ratio is ${ratio}%" rm ${SparseFile} fi echo "Done $0 $*"