想象一下,如果linux新增一块硬盘,必须对硬盘进行分区格式化,由于参数众多,若能自动创建,那就太好了,已一个10G磁盘为例,在虚拟机中添加一个10G的磁盘,然后将其分为三个分区,第一个分区 5G,第二个分区2G,剩下的都给第三个分区;下面跟我一起来写一个分区脚本吧!


#!/bin/bash

LANG=zh_cngb2312

res='false'


echo "格式化磁盘"

fdisk -l 2>/dev/null | grep -o "^Disk /dev/[sh]d[a-z]"|cut -d ' ' -f2   #列出本机上的磁盘


read -p "请选择要格式化的磁盘,如:/dev/sda,按quit可退出" choice      

if [ $choice == 'quit' ]; then

    echo "程序退出"

    exit 9

fi


for line in `fdisk -l 2>/dev/null | grep -o "^Disk /dev/[sh]d[a-z]"|cut -d ' ' -f2 `


          do






                        if [[ $line == $choice ]];then





                           res='true'



                         fi

          done

                                #for循环实现输入的参数与磁盘列表想比较,确保参数正确

until [[ $res == 'true' ]];do


read -p"输入错误,请重新参数按quit退出:" choice


    for line in `fdisk -l 2>/dev/null | grep -o "^Disk /dev/[sh]d[a-z]"|cut -d ' ' -f2 `


     do


                   if [ $choice == 'quit' ]; then

                         echo "程序退出"


                         exit 9

                   fi


                   if [[ $line == $choice ]];then


                      res='true'


                   fi

    done



done





read  -p "以下操作可能会损坏数据,请确认是否继续  y | n :" yesorno



until [ $yesorno == 'y' -o $yesorno == 'n' ];do

 read  -p"参数错误,请重新确认 y | n :" yesorno


done


if [ $yesorno == 'n' ];then

     echo "取消格式化硬盘,程序退出"

     exit 9

else

    echo "开始格式化硬盘"




if=/dev/zero of=$choice bs=512 count=1            #删除磁盘上的分区



echo '

n

p

1


+5G

n

p

2


+2G

n

p

3



w ' | fdisk $choice &> /dev/null

partprobe $choice

sync

mke2fs -j ${choice}1 &> /dev/null

sleep 1

mke2fs -j ${choice}2 &> /dev/null

sleep 1

mke2fs -j ${choice}3 &> /dev/null

fi


echo "格式化成功!"

fdisk -l $choice              #显示格式化后结果。


执行效果如图 :

wKioL1LT4iPi3rTMAAJwJppWgIY166.jpg