编写shell脚本
vim /home/usb-mount.sh
#!/bin/bashACTION=$1
DEVBASE=$2
DEVICE="/dev/${DEVBASE}"# See if this drive is already mounted
MOUNT_POINT=$(/bin/mount | /bin/grep ${DEVICE} | /usr/bin/awk '{ print $3 }')do_mount()
{if [[ -n ${MOUNT_POINT} ]]; then# Already mounted, exitexit 1fi# Get info for this drive: $ID_FS_LABEL, $ID_FS_UUID, and $ID_FS_TYPEeval $(/sbin/blkid -o udev ${DEVICE})# Figure out a mount point to useLABEL=${ID_FS_LABEL}if [[ -z "${LABEL}" ]]; thenLABEL=${DEVBASE}elif /bin/grep -q " /media/${LABEL} " /etc/mtab; then# Already in use, make a unique oneLABEL+="-${DEVBASE}"fiMOUNT_POINT="/media/${LABEL}"/bin/mkdir -p ${MOUNT_POINT}# Global mount optionsOPTS="rw,relatime"# File system type specific mount optionsif [[ ${ID_FS_TYPE} == "vfat" ]]; thenOPTS+=",users,gid=100,umask=000,shortname=mixed,utf8=1,flush"fi# 这里看需要使用sudo 和 <<EOF ,一些设备直接操作硬件SD卡槽需要root权限# 无需root权限 /bin/mount ${DEVICE} ${MOUNT_POINT} 这样就行了sudo -S /bin/mount ${DEVICE} ${MOUNT_POINT} << EOF
nle
EOF# 无需root权限 也可以用下面这一段代码# if ! echo "nle" | sudo /bin/mount -o ${OPTS} ${DEVICE} ${MOUNT_POINT}; then# # Error during mount process: cleanup mountpoint# /bin/rmdir ${MOUNT_POINT}# exit 1# fi}do_unmount()
{if [[ -n ${MOUNT_POINT} ]]; then/bin/umount -l ${DEVICE}fi# Delete all empty dirs in /media that aren't being used as mount points. for f in /media/* ; doif [[ -n $(/usr/bin/find "$f" -maxdepth 0 -type d -empty) ]]; thenif ! /bin/grep -q " $f " /etc/mtab; then/bin/rmdir "$f"fifidone
}
case "${ACTION}" inadd)do_mount;;remove)do_unmount;;
esac
chmod 777 /home/usb-mount.sh
编写服务
vim /etc/systemd/system/usb-mount@.service
[Unit]
Description=Mount USB Drive on %i[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/homeusb-mount.sh add %i
ExecStop=/home/usb-mount.sh remove %i
编写udev规则
vim /etc/udev/rules.d/99-local.rules
KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/bin/systemctl start usb-mount@%k.service"
KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/bin/systemctl stop usb-mount@%k.service"
KERNEL=="sd[a-z]", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/bin/systemctl start usb-mount@%k.service"
KERNEL=="sd[a-z]", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/bin/systemctl stop usb-mount@%k.service"# 这一段其实是 挂载mmc的SD卡或者TF卡的触发
KERNEL=="mmcblk[0-9]p[0-9]", SUBSYSTEMS=="mmc",ACTION=="add", RUN+="/bin/systemctl start usb-mount@%k.service"
KERNEL=="mmcblk[0-9]p[0-9]", SUBSYSTEMS=="mmc",ACTION=="remove", RUN+="/bin/systemctl stop usb-mount@%k.service"
更新配置
sudo udevadm control --reload-rules
sudo systemctl daemon-reload
结果
这样就可以,拔插U盘和SD卡,都可以自动挂载和卸载,并创建目录了。
其他问题
文件系统问题-exfat
挂载exfat文件,需要先安装一个组件
sudo apt-get install exfat-utils# 一些设备需要root权限才可以操作
sudo mount /dev/mmcblk1p1 /media/mmcblk1p1