#!/bin/bash
# vim:et:ts=4:sw=4:
<<INFO
SCRIPYT:autodiskmount.sh
AUTHOR:anqixiang
DATE:2020-10-18
DESCRIBE:把磁碟分為一個區,並做邏輯卷
SYSTEM:CentOS 7、RedHat 7、Ubuntu16/18
WARNING:LV_NAME、DISK_CAP、MOUNT_DIR三個陣列的元素個數需一致
VERSION:1.1.0
MODIFY:
INFO
set -e
cecho(){
echo -e "\033[$1m$2\033[0m"
}
#定義邏輯卷的相關引數
VG_NAME="data" #卷組名
LV_NAME=(${VG_NAME}_app ${VG_NAME}_mysql) #以陣列的形式儲存邏輯卷名字
DISK_CAP=(30% 70%) #代表第一個邏輯卷佔30%磁碟空間,第二個佔70%
MOUNT_DIR=(/data/app /data/mysql) #邏輯卷的掛載路徑
######################功能函數######################
#檢測磁碟
Check_Disk()
{
local disk_num=$(fdisk -l |grep "${DISK_NMAE}" |wc -l)
if [ ${disk_num} -eq 0 ];then
cecho 31 "${DISK_NMAE}不存在" && exit 1
elif [ ${disk_num} -gt 1 ];then
cecho 31 "${DISK_NMAE}已分割區,請先格式化" && exit 1
fi
cecho 32 "#分割區磁碟為:${DISK_NMAE}"
}
#磁碟分割區
Divi_Disk()
{
fdisk ${DISK_NMAE} << EOF
n
p
1
wq
EOF
fdisk -l |grep "${DISK_NMAE}"
}
#建立邏輯卷
Create_Lvm()
{
#建立卷組
if ! vgs | grep -w "${VG_NAME}" >/dev/null;then
vgcreate "${VG_NAME}" "${DISK_NMAE}1"
fi
#建立邏輯卷
for((i=0;i<${#LV_NAME[@]};i++))
do
if ! lvs | grep -w "${LV_NAME[i]}" >/dev/null;then
lvcreate -n ${LV_NAME[i]} -l ${DISK_CAP[i]}VG ${VG_NAME} -y
mkfs.ext4 /dev/${VG_NAME}/${LV_NAME[i]} >/dev/null
fi
done
lvs
}
#掛載邏輯卷
Mount_Lvm()
{
for((i=0;i<${#MOUNT_DIR[@]};i++))
do
[ ! -d ${MOUNT_DIR[i]} ] && mkdir -pv ${MOUNT_DIR[i]}
local uuid=$(blkid | grep "${LV_NAME[i]}" |awk '{print $2}')
[ ! -f /etc/fstab.bak ] && cp /etc/fstab{,.bak}
sed -ri "s#(.*)${MOUNT_DIR[i]}(.*)##" /etc/fstab #防止多次寫入相同的掛載內容
echo "${uuid} ${MOUNT_DIR[i]} ext4 defaults 0 0" >> /etc/fstab
done
sed -i '/^$/d' /etc/fstab
mount -a
cecho 96 "邏輯卷建立成功"
}
#解除安裝邏輯卷
Umount_Lvm()
{
for((i=0;i<${#MOUNT_DIR[@]};i++))
do
df -h |grep -w "${MOUNT_DIR[i]}" && umount ${MOUNT_DIR[i]}
[ -d ${MOUNT_DIR[i]} ] && rm -rf ${MOUNT_DIR[i]}
if lvs | grep -w "${LV_NAME[i]}" >/dev/null;then
lvremove -f /dev/${VG_NAME}/${LV_NAME[i]}
fi
sed -ri "s#(.*)${MOUNT_DIR[i]}(.*)##" /etc/fstab
done
if vgs | grep -w "${VG_NAME}" >/dev/null;then
vgremove ${VG_NAME}
fi
sed -i '/^$/d' /etc/fstab
mount -a
#刪除磁碟分割區
fdisk ${DISK_NMAE} << EOF
d
w
EOF
lsblk
cecho 96 "邏輯卷解除安裝成功"
}
#幫助資訊
Help(){
cat << EOF
Usage:
=======================================================================
EXAMPLE:
bash autodiskmount.sh mount #建立邏輯卷
bash autodiskmount.sh umount #解除安裝邏輯卷
EOF
}
######################主函數######################
[ "$#" -ne 2 ] && Help && exit 1
DISK_NMAE=$1
if [ "x$2" == "xmount" ];then
Check_Disk
Divi_Disk
Create_Lvm
Mount_Lvm
elif [ "x$2" == "xumount" ];then
Umount_Lvm
else
Help && exit 1
fi
set +e