硬盘自动格式化 /dev/sdb:
1、列出当前系统上所有的磁盘,让用户选择,如果选择quit则退出脚本;如果用户选择错误,就让用户重新选择;
2、当用户选择后,提醒用户确认接下来的操作可能会损坏数据,并请用户确认;如果用户选择y就继续,n就退出;否则,让用户重新选择;
3、抹除那块硬盘上的所有分区(提示,抹除所有分区后执行sync命令,并让脚本睡眠3秒钟后再分区);并为其创建三个主分区,第一个为20M,第二个为512M, 第三个为128M,且第三个为swap分区类型;(提示:将分区命令通过echo传送给fdisk即可实现)
#!/bin/bash
#
echo "Initial a disk..."
echo -e "\033[31mWarning:\033[0m"
fdisk -l 2> /dev/null | grep -o "^Disk /dev/[sh]d[a-z]"
read -p "Your choice: " PARTDISK
if [ $PARTDISK == ‘quit‘ -o $PARTDISK == ‘q‘ ]; then
echo "quit"
exit 7
fi
until fdisk -l 2> /dev/null |grep -o "Disk /dev/[sh]d[a-z]" |grep "Disk $PARTDISK" >> /dev/null;do
read -p "Wrong option, Your choice again: " PARTDISK
done
read -p "will destroy all data,continue:" CHOICE
until [ $CHOICE == ‘y‘ -o $CHOICE == ‘n‘ ];do
read -p "will destroy all data,continue:" CHOICE
done
if [ $CHOICE == ‘n‘ ]; then
echo "Cancel partition, Quiting..."
exit 9
else
## Auto umount
for I in `mount | grep "/dev/sdb" | awk ‘{print $1}‘`; do
fuser -km $I
umount $I
echo "$I umount OK."
done
## Delete disk partition
dd if=/dev/zero of=$PARTDISK bs=512 count=1 &> /tmp/log.txt
echo "Deleted partition, Formating new partition..."
sync
sleep 3
## Format disk
echo ‘n
p
1
+20M
n
p
2
+512M
n
p
3
+128M
t
3
82
w‘ | fdisk $PARTDISK >> /tmp/log.txt
partprobe $PARTDISK
sync
sleep 3
## Format partition
mke2fs -j ${PARTDISK}1 >> /tmp/log.txt |echo "format ${PARTDISK}1 finished."
mke2fs -j ${PARTDISK}2 >> /tmp/log.txt |echo "format ${PARTDISK}2 finished."
mkswap ${PARTDISK}3 >> /tmp/log.txt |echo "format swap ${PARTDISK}3 finished."
fi
---end---