Skip to content

Instantly share code, notes, and snippets.

@upsuper
Last active June 27, 2026 00:42
Show Gist options
  • Select an option

  • Save upsuper/28ceedcf6ab74a3c3e947b9ba14d4883 to your computer and use it in GitHub Desktop.

Select an option

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
@matthewboteilho

matthewboteilho commented Jun 21, 2026

Copy link
Copy Markdown

@e92335i Sorry for the late reply. I didn't notice that there was comment on this script.

The serial number is not the serial number of the product, but something that the system recognize. You would need to figure out this string through /sys/bus/usb/devices/*/serial.

I keep getting a Permission Denied command when I replace the * with either usb2 or 2-2. Am I plugging in this command correctly? I can't get this binding script to function because I can't figure out the right serial ID. I'm assuming the serial string listed under lsusb is not correct either. I'm running my external with exFAT. Any help would be appreciated, thank you.

@upsuper

upsuper commented Jun 27, 2026

Copy link
Copy Markdown
Author

@matthewboteilho You would probably have to explore your device's information first by looking around in /sys/bus/usb/devices and try to figure out which one is the device you are after and then read from its serial.

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