Disk extend with the bash script
Hello, I needed a disk expansion on a Debian machine a long time ago.
Since the machine is on a VM and the disk is not automatically resized when the assigned disk is expanded, I needed to make this work easier as in Windows. I prepared 2 sh files for the 2-step disk expansion process by doing a simple search.
- Purpose of the File
Calculate the disk you have resized on the VM and process the new size on Linux if there is any change.
resize1.sh
#!/bin/bash
distro=$(cat /etc/issue | head -n 2 | tr -d “\n” | tr “[:upper:]” “[:lower:]”)
device=$(fdisk -l | grep -w 8e | head -n 1 | cut -c-8)
partcount=$(fdisk -l | grep $device | sed 1d | grep -c $device)
newpartnum=$($partcount)
startsector=$(fdisk -l | grep -w 8e | tail -1 | tr “ “ “\n” | sed “/^$/d” | head -n 3 | tail -1)
newstartsector=$(($startsector+1))
endsector=$(fdisk -l | grep sectors | head -n 1 | tr “ “ “\n” | tail -2 | head -n 1)
newendsector=$(($endsector-1))
fdisk $device <<EOF
n
p
$newpartnum
$newstartsector
$newendsector
t
$newpartnum
8e
w
EOF
The action of the content above is usually an automated version of the action you have done manually.
Get Sercan KARA’s stories in your inbox
Join Medium for free to get updates from this writer.
2. Purpose of the File
To verify the operation we performed in the previous file and to ensure that the new disk size is processed on the kernel.
resize.2sh
#!/bin/bashdevice=$(fdisk -l | grep -w 8e | head -n 1 | cut -c-8)
partnumber=$(fdisk -l | grep $device | sed 1d | grep -c $device)
pvcreate $device$partnumber
volgroupname=$(vgdisplay | grep -w “VG Name” | cut -b10- | tr -d “ “)
vgextend $volgroupname $device$partnumber
volgroupchars=$(echo $volgroupname | wc — chars)
totalchars=$(($volgroupchars+13))
lvmname=$(df -h | grep -w $volgroupname | head -n 1 | cut -b$totalchars-)
set $lvmname
lvmname=$1
lvextend -l +100%FREE /dev/$volgroupname/$lvmname
resize2fs /dev/$volgroupname/$lvmnamedf -H | grep -vE ‘^tmpfs|cdrom|udev’ | awk ‘{ print $2 “ “ $3 “ “ $4 “ “ $5 }’ | while read output;
do
echo $output
usep=$(echo $output | awk ‘{ print $1}’ | cut -d’%’ -f1 )
partition=$(echo $output | awk ‘{ print $2 }’ )done
sleep 5
The event performed in this step ensures that the new disk size we have given is overwritten on Linux and that the newly created ‘blocks’ are verified.
Mechanism
When the first file is run, you can run the second file after the machine is turned on, which will restart the machine after completing the operations.






