Last active
January 3, 2022 16:11
-
-
Save isaaclw/34fdbd163f15cfe2de780fc9d38c81bb to your computer and use it in GitHub Desktop.
Script to optimize the size of an LVM (doing "magic" if reducing) #lvm #reduce #resize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
if [ -z "$1" ] || [ -z "$2" ] || [ ! -b "$1" ]; then | |
echo "Missing a block device, and a size (in that order)"; | |
echo " example: $0 /dev/data/apps 3" | |
echo " Ensure your size is bigger than the filesystem" | |
echo " Or type 'optimal' To calculate the size" | |
echo | |
echo "Size should be in Gigabytes" | |
exit 1; | |
fi | |
if [ "$(whoami)" != 'root' ]; then | |
echo "run this as root" | |
exit 1 | |
fi | |
size="$2" | |
if [[ "$size" = *"G" ]]; then | |
size="${size::-1}" | |
elif [ "$size" == "optimal" ]; then | |
# pass | |
: | |
elif ! [[ $size =~ ^[0-9]+$ ]]; then | |
echo "Size: $size is not an integer" >&2 | |
exit 1 | |
fi | |
blockdev="$1"; | |
mount "$blockdev" 2> /dev/null | |
current="$(echo "$(df "$blockdev" --output=size | sed 1d)/(1024*1024) + 1" | bc)" | |
if [ "$2" == "optimal" ]; then | |
size="$(echo "($(df "$blockdev" --output=used | sed 1d) * 1.33333)/(1024*1024) + 1" | bc)" | |
fi | |
df -h "$blockdev" | |
echo -n "Resizing to ${size}G [N/y] " | |
read -N 1 REPLY | |
echo | |
if test "$REPLY" = "y" -o "$REPLY" = "Y"; then | |
echo "current: $current" | |
if [ "$current" -eq 0 ] || [ "$current" -gt "$size" ]; then | |
# shrinking | |
umount "$blockdev" || exit 1 | |
while mount | grep "$blockdev" > /dev/null; do | |
umount "$blockdev" | |
sleep 2; echo "Trying again" | |
done | |
e2fsck -f "$blockdev" && \ | |
resize2fs -p -M "$blockdev" && \ | |
lvresize -f -L "${size}G" "$blockdev" && \ | |
resize2fs -p "$blockdev" && \ | |
mount "$blockdev" | |
else | |
# expanding | |
sudo lvresize -L "${size}G" "$blockdev" && sudo resize2fs -p "$blockdev" | |
fi | |
else | |
echo "Cancelled by user" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment