Skip to content

Instantly share code, notes, and snippets.

@JlnWntr
Created July 14, 2025 08:45
Show Gist options
  • Save JlnWntr/01059f501f13b678d7a5c016adf6c13e to your computer and use it in GitHub Desktop.
Save JlnWntr/01059f501f13b678d7a5c016adf6c13e to your computer and use it in GitHub Desktop.
Log USB mounts in a file on Linux
#!/bin/bash
LOGFILE="$HOME/usb_mount_log.txt"
echo "Monitoring USB mount events... Logs will be saved to: $LOGFILE"
# Initialize list of currently mounted devices
existing_mounts=$(lsblk -o NAME,MOUNTPOINT -nr | awk '$2!="" {print $1}')
udevadm monitor --subsystem-match=block --udev | while read -r line; do
if echo "$line" | grep -q "add"; then
sleep 1 # Give system time to mount
current_mounts=$(lsblk -o NAME,MOUNTPOINT -nr | awk '$2!="" {print $1}')
new_mounts=$(comm -13 <(echo "$existing_mounts" | sort) <(echo "$current_mounts" | sort))
if [[ -n "$new_mounts" ]]; then
for dev in $new_mounts; do
mount_point=$(lsblk -o NAME,MOUNTPOINT -nr | grep "^$dev " | awk '{print $2}')
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
message="[$timestamp] USB device $dev mounted at $mount_point"
echo "$message" | tee -a "$LOGFILE"
notify-send "USB Device Mounted" "$dev mounted at $mount_point"
done
existing_mounts="$current_mounts"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment