SHELL脚本实现分区

时间:2023-03-09 01:02:42
SHELL脚本实现分区

写一个脚本(前提:请为虚拟机新增一块硬盘,架设它为/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 > /dev/null | grep -o "^Disk /dev/[sh]d[a-z]" read -p "Your Choose:" PARTDISK
if [ $PARTDISK == 'quit' ];then
echo "quit"
exit ;
fi
until fdisk -l > /dev/null | grep -o "Disk /dev/[sh]d[a-z]" | grep "^Disk $PARTDISK$" &> /dev/null;do
read -p "Wrong option,Your choice aging:" 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 "QUIT"
exit ;
else
dd if=/dev/zero of=$PARTDISK bs= count= &> /dev/null
sync
sleep
echo 'n
p +20M
n
p +512M
n
p n
p +128M
t w' | fdisk $PARTDISK &> /dev/null
partprobe $PARTDISK
sync
sleep
mke2fs -j ${PARTDISK} &> /dev/null
mke2fs -j ${PARTDISK} &> /dev/null
mkswap ${PARTDISK} &> /dev/null
fi

执行过程:

[root@localhost ~]# ./partdisk.sh
Initial a disk...
Warning:
Disk /dev/sda
Disk /dev/sdb
Disk /dev/sdc
Disk /dev/sdd
Your Choose:/dev/sdb
will destroy all data,continue:y
+ records in
+ records out
bytes ( B) copied, 0.0304787 s, 16.8 kB/s
[root@localhost ~]# fdisk -l Disk /dev/sda: 21.5 GB, bytes
heads, sectors/track, cylinders
Units = cylinders of * = bytes
Sector size (logical/physical): bytes / bytes
I/O size (minimum/optimal): bytes / bytes
Disk identifier: 0x00051800 Device Boot Start End Blocks Id System
/dev/sda1 * Linux
Partition does not end on cylinder boundary.
/dev/sda2 Linux swap / Solaris
Partition does not end on cylinder boundary.
/dev/sda3 Linux Disk /dev/sdb: 21.5 GB, bytes
heads, sectors/track, cylinders
Units = cylinders of * = bytes
Sector size (logical/physical): bytes / bytes
I/O size (minimum/optimal): bytes / bytes
Disk identifier: 0x18756792 Device Boot Start End Blocks Id System
/dev/sdb1 + Linux
/dev/sdb2 Linux
/dev/sdb3 + Linux swap / Solaris Disk /dev/sdc: 21.5 GB, bytes
heads, sectors/track, cylinders
Units = cylinders of * = bytes
Sector size (logical/physical): bytes / bytes
I/O size (minimum/optimal): bytes / bytes
Disk identifier: 0x00000000 Disk /dev/sdd: 21.5 GB, bytes
heads, sectors/track, cylinders
Units = cylinders of * = bytes
Sector size (logical/physical): bytes / bytes
I/O size (minimum/optimal): bytes / bytes
Disk identifier: 0x00000000 [root@localhost ~]# mount /dev/sdb1 /mnt
[root@localhost ~]# ls /mnt
lost+found
[root@localhost ~]# vi partdisk.sh
[root@localhost ~]# umount /mnt