一个脚本(前提:请为虚拟机新增一块硬盘,假设它为/dev/sdb),为指定的硬盘创建分区

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

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

3、删除那块硬盘上的所有分区(提示,抹除所有分区后执行sync命令,并让脚本睡眠3秒钟后再分区);并为其创建3个主分区

   且第三个是swap分区类型。(分区命令通过echo传送给fdisk即可实现)


#!/bin/bash

echo "Initial a disk.."

echo -e "\033[31mWarning: \033[0m"

fdisk -l | grep -o "^Disk /dev/[sh]d[a-z]"


#!/bin/bash

echo "Initial a disk.."

echo -e "\033[31mWarning: \033[0m"

fdisk -l | grep -o "^Disk /dev/[sh]d[a-z]"


read -p "Your choice: " PARTDISK

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

  echo "quit"

  exit 7

fi


until fdisk -l |grep -o "^Disk /dev/[sh]d[a-z]" | grep "^Disk $PARTDISK$" &> /dev/null;do

   read -p "Wrong option,Your choice aging:" PARTDISK

done

echo $PARTDISK


read -p "Will destroy all date,continue: " CHOICE

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

    read -p "Wrong option,Your choice aging:" CHOICE

done


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

    exit 9

echo -e "\033[31mWarning: \033[0m"

fdisk -l | grep -o "^Disk /dev/[sh]d[a-z]"


read -p "Your choice: " PARTDISK

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

  echo "quit"

  exit 7

fi


until fdisk -l |grep -o "^Disk /dev/[sh]d[a-z]" | grep "^Disk $PARTDISK$" &> /dev/null;do

echo -e "\033[31mWarning: \033[0m"

fdisk -l | grep -o "^Disk /dev/[sh]d[a-z]"


read -p "Your choice: " PARTDISK

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

  echo "quit"

  exit 7

fi


until fdisk -l |grep -o "^Disk /dev/[sh]d[a-z]" | grep "^Disk $PARTDISK$" &> /dev/null;do

   read -p "Wrong option,Your choice aging:" PARTDISK

done

echo $PARTDISK


read -p "Will destroy all date,continue: " CHOICE

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

    read -p "Wrong option,Your choice aging:" CHOICE

done


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

    exit 9

else

dd if=/dev/zero of=$PARTDISK  bs=512 count=1 &> /dev/null

sync

echo '

n

p

1


+20M

n

p

2


+512M

n

p

3


+100M

t

3

82

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

partprobe $PARTDISK

sync

sleep 2

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

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

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

fi





 删除一个磁盘的所有分区,只需要覆盖它的MBR就可以了。

dd if=/dev/zero of=/dev/sdb bs=/dev/sdb bs=512 count=1

然后同步到磁盘sync 注:任何操作都是现在内存中完成然后才同步到磁盘上,我们可以手动同步到磁盘。

为了给同步的时间,需要sleep睡3秒。