Skip to content

Instantly share code, notes, and snippets.

@upsuper
Last active September 23, 2024 08:31
Show Gist options
  • Save upsuper/28ceedcf6ab74a3c3e947b9ba14d4883 to your computer and use it in GitHub Desktop.
Save upsuper/28ceedcf6ab74a3c3e947b9ba14d4883 to your computer and use it in GitHub Desktop.
Script to automatically bind and unbind external USB drive on Synology NAS
#!/bin/bash
SERIAL="00000000"
echo "Looking for device with serial $SERIAL..."
for d in /sys/bus/usb/devices/*-*; do
if [[ -f "$d/serial" ]]; then
serial=$(<"$d/serial")
if [[ "$serial" = "$SERIAL" ]]; then
device="$(basename $d)"
break
fi
fi
done
if [[ -z "$device" ]]; then
echo "Fail to find device with serial $SERIAL"
exit 1
fi
echo "Binding device $device..."
echo "$device" > /sys/bus/usb/drivers/usb/bind || exit 1
echo -n "Waiting for filesystem to mount... "
exec 3< <(tail -f -n1 /var/log/kern.log)
while read line; do
if [[ "$line" = *"[EXFAT] mounted successfully" ]]; then
echo "Mounted!"
break
elif [[ "$line" = *"usb $device: "* && "$line" = *" error "* ]]; then
echo "Error!"
exit 1
fi
done <&3
echo -n "Waiting for filesystem to unmount... "
while read line; do
if [[ "$line" = *"[EXFAT] unmounted successfully" ]]; then
echo "Unmounted!"
break;
fi
done <&3
echo "Unbinding device $device..."
echo "$device" > /sys/bus/usb/drivers/usb/unbind
@schor123
Copy link

ok, I ran your script as sudo in the ssh console: in the GUI I see the external hdd gets mounted, however, the script stops at 'waiting for the
filesystem to mount'. Apparently, kern.log doesn't output the 'mounted successfully' option:
image

Any ideas?

@schor123
Copy link

schor123 commented Apr 12, 2021

Also, un-mounting (=ejecting) the device via the GUI just adds one single line to kern.log:
image
so I suppose the next part of the script also won't recognize unmounting the hdd

Also, don't you need to put
exec 3< <(tail -f -n1 /var/log/kern.log)
in front of
echo -n "Waiting for filesystem to unmount... " while read line; do if [[ "$line" = *"[EXFAT] unmounted successfully" ]]; then echo "Unmounted!" break; fi done <&3
, as well, in order to read the kern.log?

Thanks!

@upsuper
Copy link
Author

upsuper commented Apr 13, 2021

The script here relies on the log from kernel, and it apparently supports only exFAT filesystem. I have no idea about your system and external disk so I can't really provide any advice. There is probably a better way to detect mounting and unmounting... but as it's working for me, I'm not very motivated to investigate further.

Also, don't you need to put
exec 3< <(tail -f -n1 /var/log/kern.log)
in front of

no, actually that would probably be wrong, IIRC. The previous one would be reused by the second loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment