脚本实现重新对一个磁盘分区格式化

主要分为三步
1. 删除原有分区
2. 使用fdisk进行分区
3. 创建文件系统

#!/bin/bash
#
disks=$(fdisk -l 2>/dev/null |grep '^Disk /dev/[sh]d[a-z]'  |awk -F: '{print $1}' |cut -d' ' -f2 |awk -F '/' '{print $3}' |tr '\n' ' ')


repartition(){
    echo "Disk: $disks"
    read -p "Input which disk you want re-partition: " disk
    echo -e "Step 1: delete all partion of $disk "
    read -p "[y/n]" x
    if [ $x = 'y' ]; then
        dd if=/dev/zero of=/dev/$disk bs=512 count=1
        echo "partition of $disk delete complete."
    else
        exit 0
    fi
    echo "Step 2: re-partition $disk"
    echo 'n
p
1

+20M
n
p
2

+512M
n
p
3

+128M
t
3
82
w' | fdisk /dev/$disk &>/dev/null
    sleep 3
    sync

    # create filesystem
    echo "Step 3: create filesystem"
    mkfs.ext4 /dev/${disk}1 &>/dev/null
    mkfs.ext4 /dev/${disk}2 &>/dev/null
    mkswap /dev/${disk}3 &>/dev/null
    sleep 3
}

while true; do
    read -p "Input your choice: [q]-->quit, [n]-->re-partition: " choice
    if [ $choice = 'q' ]; then
        exit 0
    elif [ $choice = 'n' ]; then
        read -p "Warning: the operation may destroy your data
    Are you sure continue [y/n]" confirm
        if [ $confirm = 'y' ]; then
            repartition
        else
            exit 0
        fi
    else
        echo "Your input is invalid, plz input again!"
    fi
done

你可能感兴趣的:(bash,shell)