SoFunction
Updated on 2025-03-09

Quickly create formatted disks and detailed operation steps for shell scripts

This article introduces you how to use shell scripts to implement partition formatting and mount a disk. The specific content is as follows:

Check the current disk partition status

Check the current partition status of a disk, use the command: fdisk -l

fdisk -l
//View disk informationlsblk

Let the hard disk enter partition mode

fdisk /dev/sdb

Order(enter m Get help): m //Print options menu
Add a new partition:
Order(enter m Get help):n //Add a partition
Select a partition type:
Select (default p): e 
//Enter e indicates the creation of an extended partition
Number of partitions:
Partition number (1-4,default 1):1

Set up sectors:
Start Sectors (2048-83886079,default为 2048):Enter 
Last Sectors, +Sectors or +size{K,M,G} (2048-83886079,default为 83886079):Enter

save
Order(enter m Get help):w //save退出

Format operation, you can mount it and use it after completion

mkfs -t ext3 /dev/sdb

//mount the file system and mirror the ISO to the specified folder.//temporary:mount /dev/cdrom(Source File) /mnt(Source load point)
//permanent:vi /etc/fstab
dev/sdb /mnt iso9660 default 0 0

Create, format, and mount newly added disk scripts through administrator selection

Note: Create the disk first

#! /bin/bash
#Use shell script to implement partition format mount of a diskPS3="Prompt to select the disk to create:"
select W in `ls /dev/sd*|grep -o 'sd[b-z]'|uniq` quit
do
  case $W in
  sda)
   fdisk -l /dev/sda
   break;;
  sd[b-z])
    echo "n
      p

      w" | fdisk /dev/$W
   -i size=512 /dev/${W}"1" &>/dev/null
  mkdir -p /data/${W}"1" &>/dev/null
  echo -e "/dev/${W}"1" /data/${W}"1" xfs defaults 0 0\n" >> /etc/fstab
  mount -a &>/dev/null
  break;;
  quit)
  break;;
  *)
  echo "The wrong disk,Please check again";;
  esac
done  

Automatically create, format and mount newly added disk scripts

#!/bin/bash
useshellScript implementation partition format mounts a disk

for V in $(ls /dev/sd[b-z])
do
 echo -e "n\np\n\n\n\nw\n" |fdisk $V
  -i size=512 ${V}1 &>/dev/null
 sleep 1
 M=$(echo "$V" |awk -F "/" '{print $3}')
 mkdir -p /data/${M}1 &>/dev/null
 echo -e "${V}1 /data/${M}1 xfs defaults 0 0\n" >>/etc/fstab
 mount -a &>/dev/null
done

Cancel the mount

 umount /dev/sdb

Delete the partition

Note: Enter the disk session

fdisk /dev/sdb 

//Enter partition modem d 1 Operation in turn

This is the article about quickly creating formatted disks and detailed operation steps for shell scripts. For more related shell scripts, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!