Skip to content

Instantly share code, notes, and snippets.

@kiler129
Created May 18, 2025 09:42
Show Gist options
  • Save kiler129/53c18f00e175e334b0e69accc40f8330 to your computer and use it in GitHub Desktop.
Save kiler129/53c18f00e175e334b0e69accc40f8330 to your computer and use it in GitHub Desktop.
Udev example to symlink UPS devices in /dev/ups
SUBSYSTEM=="usb", ATTR{idVendor}=="0463", ATTR{idProduct}=="ffff", PROGRAM="/usr/local/bin/nut-usbups-name", SYMLINK+="ups/%c"
#!/bin/sh
set -e -o errexit -o pipefail -o nounset
# udev scripts are called w/o environment; depending on the distro sed can be provided in many ways (standalone, busyboxy etc)
PATH="/usr/local/bin:/usr/bin:/bin"
if ! command -v sed 2>&1 >/dev/null; then
echo "sed is required by $0" >&2
exit 1
fi
# Ensure the string is safe to use in a filesystem path
# Converts any non-alphanumeric to _ w/o duplicates & trim whitespaces
sanitize() {
echo "$1" | sed -E 's/[^a-zA-Z0-9]+/_/g; s/^_+//; s/_+$//'
}
# Prepare safe name parts, with fallback to hex IDs
vendor=$(sanitize "${ID_VENDOR:-}")
model=$(sanitize "${ID_MODEL:-}")
: ${vendor:=$(sanitize "${ID_VENDOR_ID}")}
: ${model:=$(sanitize "${ID_MODEL_ID}")}
# If tr is available, try avoiding duplicated vendor name in model
if command -v tr 2>&1 >/dev/null; then
vendorLC=$(echo "$vendor" | tr '[:upper:]' '[:lower:]')
modelLC=$(echo "$model" | tr '[:upper:]' '[:lower:]')
if [ "${modelLC#"$vendorLC"}" = "$modelLC" ]; then
model="${vendor}-${model}"
fi
else
model="${vendor}-${model}"
fi
# Add serial, if available, to make name unique
devName="${ID_BUS}-$model"
serial=$(sanitize "${ID_SERIAL_SHORT:-}")
if ! [ -z "$serial" ]; then
devName="${devName}-$serial"
fi
echo $devName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment