Skip to content

Instantly share code, notes, and snippets.

@erwin
Last active July 6, 2024 09:58
Show Gist options
  • Save erwin/a66a4c3f8a5d940ab6c434b48568ff39 to your computer and use it in GitHub Desktop.
Save erwin/a66a4c3f8a5d940ab6c434b48568ff39 to your computer and use it in GitHub Desktop.
Shell Script to Disconnect / Reconnect USB device
#!/bin/bash
# In my case, I would like to turn off my HUGE TRACKBALL sometimes, because it
# gets disconnected from the USB bus... Not very often, but a few times per month
# I launch this script with a tool like `rofi` or `dmenu`.
#
# You can easily adjust this script to work for any USB device by changing the
# these variables for the hex code of vendor and product.
#
#
#VENDOR="056e"
#PRODUCT="010d"
#
# You get these codes from lsusb
if [[ $EUID -ne 0 ]]; then
exec sudo /bin/bash "$0" "$@"
echo "This script must be run as root" 1>&2
echo " Root permission required to write to /sys/bus/usb/devices"
exit 1
fi
echo "
o o o o o-o o--o o-O-o o--o O o-o o o o--o O o o
| | | | o | | | | / \ / | / | | / \ | |
O--O | | | -o O-o o-o | O-Oo o---oO OO O--o o---o| |
| | | | o | | | | \ | | \ | \ | | | || |
o o o-o o-o o--o o o o o o o-o o o o--o o oO---oO---o
"
set -euo pipefail
IFS=$'\n\t'
# Bus 001 Device 068: ID 056e:010d Elecom Co., Ltd HUGE TrackBall
VENDOR="056e"
PRODUCT="010d"
for DIR in $(find /sys/bus/usb/devices/ -maxdepth 1 -type l); do
if [[ -f $DIR/idVendor && -f $DIR/idProduct &&
$(cat $DIR/idVendor) == $VENDOR && $(cat $DIR/idProduct) == $PRODUCT ]]; then
DEVICE=$(basename $DIR)
echo "Device: $DEVICE"
echo "Path: $DIR"
echo
echo
echo "Unbinding USB Device"
echo $DEVICE > /sys/bus/usb/drivers/usb/unbind
sleep 1
echo "Rebinding USB Device"
echo $DEVICE > /sys/bus/usb/drivers/usb/bind
sleep 1
echo "Trying the usb/authorized way..."
echo "Disconnecting..."
echo 0 > $DIR/authorized
sleep 1
echo "Reconnecting..."
echo 1 > $DIR/authorized
fi
done
echo
echo "Complete"
notify-send "Reconnect Complete" "Huge Trackball Reconnection Complete"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment