马哥教育视频学习笔记-shell脚本完成磁盘分区格式化-http://edu.51cto.com/lesson/id-28201.html
以下是脚本内容,内容比较简单,不做详解
在Linux上准备一块空闲的磁盘即可,如何分区可以在脚本内改下
#!/bin/bash
#
echo "Initial a disk..."
echo -e "\033[31mWarning: \033[0m "
#开始的说明信息,其中Warning以红色字体显示
fdisk -l 2> /dev/null | grep -o "^Disk /dev/[sh]d[a-z]"
#显示所有磁盘设备
read -p "Your choice(Disk or quit):" PARTDISK
if [ $PARTDISK == ‘quit‘ ]; then
echo "quit"
exit 7
fi
for I in `mount | grep "$PARTDISK" | awk ‘{print $1}‘`;do
fuser -km $I
umount $I
echo "$I umount ok."
done
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(y or n):" CHOICE
until [ $CHOICE == ‘y‘ -o $CHOICE == ‘n‘ ]; do
read -p "Will destroy all data, continue(y or n):" CHOICE
done
if [ $CHOICE == ‘n‘ ]; then
echo "Quit"
exit 9
else
dd if=/dev/zero of=$PARTDISK bs=512 count=1 &> /dev/null
sync
sleep 3
echo ‘n
p
1
+2G
n
p
2
+3G
n
p
3
+1G
w‘ | fdisk $PARTDISK &> /dev/null
partprobe $PARTDISK
sync
sleep 2
mkfs.ext4 ${PARTDISK}1 &> /dev/null
mkfs.ext4 ${PARTDISK}2 &> /dev/null
mkswap ${PARTDISK}3 &> /dev/null
fi
fdisk -l $PARTDISK
#查看分区结果