shell腳本自動(dòng)分區、創建邏輯卷
發表時間:2020-10-19
發布人:葵宇科技
浏覽次數:47
#!/bin/bash
# vim:et:ts=4:sw=4:
<<INFO
SCRIPYT:autodiskmount.sh
AUTHOR:anqixiang
DATE:2020-10-18
DESCRIBE:把磁盤分為一個(gè)區,并做邏輯卷
SYSTEM:CentOS 7、RedHat 7、Ubuntu16/18
WARNING:LV_NAME、DISK_CAP、MOUNT_DIR三個(gè)數組的元素個(gè)數需一緻
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%) #代表第一個(gè)邏輯卷占30%磁盤空間,第二個(gè)占70%
MOUNT_DIR=(/data/app /data/mysql) #邏輯卷的挂載路(lù)徑
######################功能函數######################
#檢測磁盤
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