挂载在树莓派上的硬盘经常自己取消了挂载,就改写了一个自动检测并挂载硬盘的Shell脚本
代码改自:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#!/bin/sh # 判断是否挂载 IS_MOUNT=`df -h | grep /home/pi/Disk | wc -l` DISK_NAME=`lsblk -l | awk '{if ($3=="0") print}' | grep sda | awk '{print $1}'` if [ $IS_MOUNT -eq 0 ]; then echo 硬盘未挂载 # 获取硬盘地址 判断硬盘地址是否存在 if [ -b /dev/$DISK_NAME ]; then echo 硬盘即将挂载 mount /dev/$DISK_NAME /home/pi/Disk sync else echo 设备不存在 fi elif [ $IS_MOUNT -eq 1 ]; then echo 硬盘已挂载 else echo ERROR fi
|
开机自动挂载硬盘
获取硬盘 UUID
1
|
blkid -s UUID /dev/sda1
|
写入配置
1 2 3 4
|
vim /etc/fstab
# 配置 UUID=9032ef41-46cf-4bc6-ac01-be54be5f6c49 /data ext4 defaults 0 0
|
使用UUID挂载
最近新购入了一块硬盘,不知道是树莓派供电不足还是什么原因,开机后硬盘设备不太稳定,有时是 /dev/sda1
有时候又是 /dev/sdb1
,之前的脚本就会出现问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export PATH
# 判断硬盘是否已挂载和处理挂载点冲突 TIME=$(date "+%Y-%m-%d %H:%M:%S") LOG_FILE="/home/zh/sh/.chickDiskLog" MOUNT_POINT="/mnt/Disk" UUID="34aada44-e3e6-4a7e-b02d-66e672d3ec24" # 替换为你的硬盘UUID
# 检查硬盘是否挂载 IS_MOUNT=$(findmnt -rn -S UUID=$UUID -o TARGET)
if [ -z $IS_MOUNT ]; then echo "$TIME 硬盘未挂载" >> $LOG_FILE
# 检查挂载点是否被占用 MOUNTED=$(mount | grep -w $MOUNT_POINT | wc -l)
if [ $MOUNTED -ne 0 ]; then echo "$TIME 挂载点已被占用,尝试卸载当前设备" >> $LOG_FILE umount $MOUNT_POINT if [ $? -ne 0 ]; then echo "$TIME 卸载失败,挂载中止" >> $LOG_FILE exit 1 fi echo "$TIME 卸载成功" >> $LOG_FILE fi
# 判断 UUID 是否存在 if blkid | grep -q "UUID=\"$UUID\""; then # 处理 systemd 提示 sudo systemctl daemon-reload
# 挂载设备 mount UUID=$UUID $MOUNT_POINT sync
if [ $? -eq 0 ]; then echo "$TIME 已挂载新设备" >> $LOG_FILE else echo "$TIME 挂载失败" >> $LOG_FILE fi else echo "$TIME 设备不存在" >> $LOG_FILE fi elif [ "$IS_MOUNT" = "$MOUNT_POINT" ]; then echo "$TIME 硬盘已挂载" >> $LOG_FILE else echo "$TIME ERROR" >> $LOG_FILE fi
|
代码中的 systemctl daemon-reload
不是必须,
挂载时出现:mount: (hint) your fstab has been modified, but systemd still uses the old version; use 'systemctl daemon-reload' to reload.
提示的再添加