Created
December 22, 2024 04:54
-
-
Save AasSuhendar/e331894b091e1b4d42b4ac84e02c56a3 to your computer and use it in GitHub Desktop.
Script for Format Partition that have installed LVM
This file contains hidden or 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 | |
| # Script to format /dev/sdb by removing LVM and creating a new filesystem. | |
| # WARNING: This script will DELETE ALL DATA on /dev/sdb. | |
| DEVICE="/dev/sdb" | |
| PARTITION="${DEVICE}1" | |
| # Function to check and ensure the script is run as root. | |
| check_root() { | |
| if [[ $EUID -ne 0 ]]; then | |
| echo "This script must be run as root." >&2 | |
| exit 1 | |
| fi | |
| } | |
| # Confirm with the user before proceeding. | |
| confirm_action() { | |
| read -p "WARNING: This will erase all data on $DEVICE. Are you sure? (yes/no): " CONFIRM | |
| if [[ "$CONFIRM" != "yes" ]]; then | |
| echo "Aborted." | |
| exit 0 | |
| fi | |
| } | |
| # Deactivate logical volumes | |
| deactivate_lvs() { | |
| echo "Deactivating logical volumes..." | |
| lvchange -an "$DEVICE"* 2>/dev/null | |
| } | |
| # Remove logical volumes | |
| remove_lvs() { | |
| echo "Removing logical volumes..." | |
| lvremove -f "$(lvdisplay | grep 'LV Path' | awk '{print $3}')" 2>/dev/null || echo "No logical volumes found." | |
| } | |
| # Remove volume groups | |
| remove_vgs() { | |
| echo "Removing volume groups..." | |
| vgremove -f "$(vgdisplay | grep 'VG Name' | awk '{print $3}')" 2>/dev/null || echo "No volume groups found." | |
| } | |
| # Remove physical volumes | |
| remove_pvs() { | |
| echo "Removing physical volumes..." | |
| pvremove -ff "$DEVICE" 2>/dev/null || echo "No physical volumes found on $DEVICE." | |
| } | |
| # Wipe the partition | |
| wipe_partition() { | |
| echo "Wiping $DEVICE..." | |
| wipefs -a "$DEVICE" | |
| dd if=/dev/zero of="$DEVICE" bs=1M status=progress count=100 | |
| } | |
| # Create a new partition and format | |
| create_partition() { | |
| echo "Creating a new partition table..." | |
| parted "$DEVICE" mklabel gpt --script | |
| parted "$DEVICE" mkpart primary ext4 0% 100% --script | |
| echo "Formatting the new partition with ext4..." | |
| mkfs.ext4 "$PARTITION" | |
| } | |
| # Main execution | |
| main() { | |
| check_root | |
| confirm_action | |
| deactivate_lvs | |
| remove_lvs | |
| remove_vgs | |
| remove_pvs | |
| wipe_partition | |
| ##create_partition | |
| echo "Operation completed. $PARTITION is now formatted and ready for use." | |
| } | |
| # Run the main function | |
| main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment