Search code examples
linuxbashinotifywait

output mountpoint on (usb)device detection


I want to create a bash script that will output the mount point from an inserted USB device. I have two commands (between "do" "and" done") that work separately but not together in a bash script. The script looks for a UUID file use the $UUID filename in the lsblk command to extract the mountpoint The mount point must be in a variable so that I can continue to use this in the same bash script. I've had this so far:

    #!/bin/bash 

EXCLUDE_DEVICE_1="5F92-0F71"
EXCLUDE_DEVICE_2="6fd9f710-f897-4b13-a521-70e184f669f3"

inotifywait -m --exclude "($EXCLUDE_DEVICE_1|$EXCLUDE_DEVICE_2)" -e create --format '%f' /dev/disk/by-uuid/ \
        | while read UUID
                do 
                        echo "new device found with uuid $UUID"
                        lsblk --noheadings --output MOUNTPOINT /dev/disk/by-uuid/$UUID
                done

The echo new device works and can see the $UUID but the lsblk command does nothing. When put the command lsblk --noheadings --output MOUNTPOINT /dev/disk/by-uuid/**realuuid** in the terminal it works. does anyone know what's wrong?


Solution

  • The problem was a timing issue and can be solved by adding (for me) minimum sleep time of 0.2 sec between detecting and executing the command

    
    EXCLUDE_DEVICE_1="5F92-0F71"
    EXCLUDE_DEVICE_2="6fd9f710-f897-4b13-a521-70e184f669f3"
    LOG_FILE=/home/user/Documents/log.txt
    
    exec > >(tee -a $LOG_FILE)
    exec 2>&1
    
    inotifywait -m --exclude "($EXCLUDE_DEVICE_1|$EXCLUDE_DEVICE_2)" -e create --format '%f' /dev/disk/by-uuid/ \
            | while read UUID
                    do 
                            echo "new device found with uuid: $UUID"
                            sleep 0.2
                            lsblk --noheadings --output MOUNTPOINT /dev/disk/by-uuid/$UUID
                    done