Guest User

Untitled

a guest
Jun 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. #!/usr/bin/env bash
  2.  
  3. if [[ -z "$1" ]]; then
  4. echo -e "usage: sudo $0 <file.img>\n"
  5. exit
  6. fi
  7.  
  8. if [[ $(whoami) != "root" ]]; then
  9. echo -e "error: this must be run as root: sudo $0 <file.img>"
  10. exit
  11. fi
  12.  
  13.  
  14. if [[ ! -e "$1" ]]; then
  15. echo -e "error: no such file\n"
  16. exit
  17. fi
  18.  
  19. orig_img_size=$(stat --printf="%s" "$1")
  20.  
  21. part_info=$(parted -m "$1" unit B print)
  22. echo -e "\n[+] partition info"
  23. echo "----------------------------------------------"
  24. echo -e "$part_info\n"
  25.  
  26. part_num=$(echo "$part_info" | grep ext4 | cut -d':' -f1)
  27. part_start=$(echo "$part_info" | grep ext4 | cut -d':' -f2 | sed 's/B//g')
  28. part_size=$(echo "$part_info" | grep ext4 | cut -d':' -f4 | sed 's/B//g')
  29.  
  30. echo -e "[+] setting up loopback\n"
  31. loopback=$(losetup -f --show -o "$part_start" "$1")
  32.  
  33. echo "[+] checking loopback file system"
  34. echo "----------------------------------------------"
  35. e2fsck -f "$loopback"
  36.  
  37. echo -e "\n[+] determining minimum partition size"
  38. min_size=$(resize2fs -P "$loopback" | cut -d':' -f2)
  39.  
  40. # next line is optional: comment out to remove 1% overhead to fs size
  41. min_size=$(($min_size + $min_size / 100))
  42.  
  43. if [[ $part_size -lt $(($min_size * 4096 + 1048576)) ]]; then
  44. echo -e "\n[!] halt: image already as small as possible.\n"
  45. losetup -d "$loopback"
  46. exit
  47. fi
  48.  
  49. echo -e "\n[+] resizing loopback fs (may take a while)"
  50. echo "----------------------------------------------"
  51. resize2fs -p "$loopback" "$min_size"
  52. sleep 1
  53.  
  54. echo -e "[+] detaching loopback\n"
  55. losetup -d "$loopback"
  56.  
  57. part_new_size=$(($min_size * 4096))
  58. part_new_end=$(($part_start + $part_new_size))
  59.  
  60. echo -e "[+] adjusting partitions\n"
  61. parted "$1" rm "$part_num"
  62. parted "$1" unit B mkpart primary $part_start $part_new_end
  63.  
  64. free_space_start=$(parted -m "$1" unit B print free | tail -1 | cut -d':' -f2 | sed 's/B//g')
  65.  
  66. echo -e "[+] truncating image\n"
  67. truncate -s $free_space_start "$1"
  68.  
  69. new_img_size=$(stat --printf="%s" "$1")
  70. bytes_saved=$(($orig_img_size - $new_img_size))
  71. echo -e "DONE: reduced "$1" by $(($bytes_saved/1024))KiB ($((bytes_saved/1024/1024))MB)\n"
Add Comment
Please, Sign In to add comment