Shell脚本-自动分区

---整理自马哥教学视频

写一个脚本,为指定的硬盘创建分区:

1, 列出当前统上所有磁盘,让用户选择,如果选择quit则退出脚本;如果选择错误,就让用户重新选择

2, 当用户选择后,提醒用户确认接下来的操作可能损坏数据,并请用户确认;如果选择y就继续,选择n退出,否则让用户重新选择

3, 抹除硬盘上的所有分区,(提示:抹除所有分区后执行sync命令,并让脚本睡眠3秒后再分区);并为其创建三个主分区,第一个20M,第二个512M,第三个128M,且第三个为swap分区;(提示:将分区命令通过echo传送给fdisk即可实现)

#!/bin/bash


fdisk -l 2> /dev/null | egrep "^Disk /dev/[s,h]d[[:alpha:]]" | awk -F: '{print $1}'
read -p "Please input the device path that you want to set:" choice1

until fdisk -l 2> /dev/null | egrep "^Disk /dev/[s,h]d[[:alpha:]]" | awk -F: '{print $1}'  | egrep "^Disk $choice1$" &> /dev/null
do
	[ $choice1 == "quit" ] && echo "Quiting..."  && exit 8
	read -p "Please input the device path that you want to set:" choice1
done
read -p  "Your choice is $choice1, Partition will damamge the data, Please confirm(y|n):" choice2
until [ $choice2 == "y"  -o $choice2 == "Y" -o $choice2 == "n" -o $choice2 == "N" ]
do
	read -p  "Your choice is $choice2 ,Partition will damamge the data, Please confirm(y|n):" choice2
done	
if [ $choice2 == "N" -o $choice2 == "n" ]
then
	echo "Quiting.." 
	exit 9
else	
	df | grep $choice1 &> /dev/null  && echo "$choice1 are using. Please umount it  first." && exit 9
	echo "erasing the partition data....."	
	dd if=/dev/zero of=$choice1 bs=512 count=1 &> /dev/null
	sync &&	sleep 3	
	partprobe $choice1
	echo "Creating new partition..."
echo 'n
p
1

+20M
n
p
2

+512M
n

3

+128M
t
3
82
w' | fdisk $choice1 &> /dev/null
	sync && sleep 3
	partprobe $choice1
	echo "creating filesystem..."
	mke2fs -j ${choice1}1 &> /dev/null
	mke2fs -j ${choice1}2 &> /dev/null
	mkswap ${choice3} &> /dev/null
	mkdir -p /data/test1 /data/test2
	df  | grep ${choice1}1 &> /dev/null && umount ${choice1}1  
	df  | grep ${choice1}2 &> /dev/null && umount ${choice1}2 
	mount ${choice1}1 /data/test1
	mount ${choice1}2 /data/test2
	swapon ${choice1}3  &> /dev/null
	echo "The new filesystem has been mounted in /data/test"	
fi

 

你可能感兴趣的:(Shell)