Skip to content

Instantly share code, notes, and snippets.

@fenar
Created June 12, 2024 17:43
Show Gist options
  • Save fenar/602e671dbb0e8694310851c6ee47d145 to your computer and use it in GitHub Desktop.
Save fenar/602e671dbb0e8694310851c6ee47d145 to your computer and use it in GitHub Desktop.
Format All Disks
#!/bin/bash
# Ensure the script is run as root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root"
exit
fi
# List all the hard drives
drives=$(lsblk -dpno NAME,TYPE | grep 'disk' | awk '{print $1}')
# Function to clean up LVM and reformat a drive
clean_up_and_reformat_drive() {
local drive=$1
echo "Cleaning up LVM on $drive..."
# Deactivate all logical volumes
lvs=$(lvdisplay | grep "LV Path" | awk '{print $3}')
for lv in $lvs; do
lvchange -an $lv
lvremove -f $lv
done
# Remove volume groups
vgs=$(vgdisplay | grep "VG Name" | awk '{print $3}')
for vg in $vgs; do
vgchange -an $vg
vgremove -f $vg
done
# Remove physical volumes
pvs=$(pvdisplay | grep "PV Name" | awk '{print $3}')
for pv in $pvs; do
pvremove -ff $pv
done
echo "Reformatting $drive..."
# Unmount all partitions on the drive
for partition in $(lsblk -ln $drive | awk '{print $1}'); do
umount -f /dev/$partition 2>/dev/null
swapoff /dev/$partition 2>/dev/null
done
# Create a new partition table (GPT) and partition using sfdisk
echo ",,L" | sfdisk $drive --delete --force
# Re-read the partition table
partx -u $drive
# Wait a moment to ensure the kernel recognizes the changes
sleep 1
# Format the new partition with ext4 filesystem
mkfs.ext4 -F ${drive}1
echo "$drive reformatted successfully."
}
# Loop through each drive and clean up LVM and reformat it
for drive in $drives; do
clean_up_and_reformat_drive $drive
done
echo "All drives have been cleaned up and reformatted."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment