Linux实现磁盘自动挂载
#!/bin/bash
function format_disk() {
read -p "是否格式化硬盘(y or n): " response
if [[ $response == 'y' || $response == "yes" ]]; then
echo "——————————正在格式化$1—————————————"
mkfs -t ext4 $1
echo "——————————————格式化结束——————————————"
else
echo "————————跳过格式化$1————————————"
fi
}
function backup_home() {
read -p "是否备份home目录(y or n): " response
if [[ $response == 'y' || $response == "yes" ]]; then
read -p "输入备份位置: " backup_location
if [ ! -d $backup_location ]; then
mkdir $backup_location
echo "————————备份位置创建成功!————————"
fi
echo "————————————开始备份————————————"
mount $1 $backup_location
cp -a /home/* $backup_location
echo "————————————备份完成————————————"
umount $1
rm -rf $backup_location
else
echo "————————————跳过备份————————————"
fi
read -p "输入临时挂载路径:" temporary_mount
if [ ! -d $temporary_mount ]; then
mkdir $temporary_mount
echo "————————临时挂载位置创建成功!————————"
fi
echo "————————————开始挂载————————————"
mount $1 $temporary_mount
df -h | grep $1
echo "——————————临时挂载完成———————————"
}
function auto_mount() {
echo "————————设置开机自动挂载——————————"
while true; do
read -p "输入自动挂载位置: " auto_mount_location
if [ -d $auto_mount_location ]; then
if [ -f /etc/rc.local ]; then
# 读取已有的/etc/rc.local内容
existing_content=$(cat /etc/rc.local)
if ! grep -q "mount $1 $auto_mount_location" <<<"$existing_content"; then
# 追加新的挂载信息
echo "mount $1 $auto_mount_location" >>/etc/rc.local
echo "$existing_content" >/etc/rc.local
chmod +x /etc/rc.local
echo "————————————成功设置自动挂载到$auto_mount_location———————————"
else
echo "该挂载已存在于/etc/rc.local中,不需要重复设置。"
fi
else
# 此时/etc/rc.local文件不存在,新创建文件并添加头信息
touch /etc/rc.local
echo "#!/bin/bash" >/etc/rc.local
echo "mount $1 $auto_mount_location" >>/etc/rc.local
chmod +x /etc/rc.local
echo "——————————成功设置自动挂载到$auto_mount_location—————————"
fi
break
else
read -p "自动挂载位置$auto_mount_location不存在,是否创建?(y or n)!" response
if [[ $response == "y" || $response == "yes" ]]; then
mkdir $auto_mount_location
echo "————————————创建挂载位置$auto_mount_location————————————"
else
echo "——————————————不创建重新输入——————————————"
fi
fi
done
}
read -p "请输入要操作的硬盘号:" disk_number
if $(fdisk -l | grep -q $disk_number); then
format_disk $disk_number
backup_home $disk_number
auto_mount $disk_number
else
echo "驱动号输入错误!"
fi
数据无价,谨慎操作