Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Shell 編程:自動建立磁碟分區

用 shell 腳本自動新增分區,已實現的功能有:

1. 檢查是否有擴展分區、是否可新增,若可則把剩餘空間全部設為擴展分區。

2. 當擴展分區已存在,則提示輸入要新增的分區大小,僅接受大於 1 的正整數。

程式碼如下:

#!/bin/bash
Hard='/dev/sda'
Exten=`fdisk -l $Hard|grep Extended`
Maxnum=`fdisk -l $Hard|grep -o "^/dev/sda[1-9]\>"|tr -d [[:punct:]]|tr -d 'A-Za-z'|sort -n|tail -1`
if [[ -z $Exten ]];then
       if [[ $Maxnum -ge 4 ]];then
                echo "Disk partitions error!..."
                exit 1
             elif [ $Maxnum -eq 1 -o $Maxnum -eq 2 ];then
                cat << EOF
                e|E)use all free disk greate is Extended;
                *)Quit;
EOF
                Sdanum=$((Maxnum+1))
                read Opt
                case $Opt in
                e|E)
fdisk $Hard &> /opt/fdisk.log <<EOF
n
e
$Sdanum
w
EOF
                ;;
                *)
                echo "None operating ,Exit"
                exit 2
                ;;
                esac
        else
                cat << EOF
        e|E)use all free disk greate is Extended;
        *)Quit;
EOF
                read Opt
                case $Opt in
                e|E)
                fdisk $Hard &> /opt/fdisk.log <<EOF
                n
                e
               
                w
EOF
                ;;
                *)
                echo "None operating ,Exit"
                exit 2
                ;;
                esac
        fi
else
       echo 'Please input new partition size(MB),Only number.'
       read Size
       Pun=`echo "$Size"|grep "[[:punct:]]\+"`
                while [[ $Size -le 1 || -n $Pun ]]
                do
                        echo "Wrong try again!"
                        read Size
                        Pun=`echo "$Size"|grep "[[:punct:]]\+"`
                done
       answer=${Size:-50}
       fdisk $Hard &> /opt/fdisk.log <<EOF
       n
       +${Size}M
       w
EOF
fi

新手作品,程式碼多有不足,歡迎各位先進指正。

Copyright © Linux教程網 All Rights Reserved