2

I'm trying to build a system that will remount a USB drive when plugged in.

The USB, when plugged in, is then mapped to something like /dev/sdc1. I then want to unmount, then remount using pmount (in order to get user permissions, so another program can read/access the USB drive). The following commands I have been running manually:

  1. sudo umount /dev/sdc1
  2. pmount /dev/sdc1 some_label

I then have another program that will read the files from /media/some_label.

However, this needs to be done programmatically. I have created the following udev rule:

ACTION=="add", \
ATTRS{idVendor}=="154b", \
ATTRS{idProduct}=="00ed", \
RUN+="/usr/bin/bash /home/some/script/location/script.sh"

I know it's being run because I can change the run command to mkdir and I see the (test) directory is created when I plug in my USB.

However, I'm unsure of how to find the device path (/dev/sdc1) programmatically in a shell script. With that, I'm able to run those 2 commands I listed above.

Any suggestions?

Some Guy
  • 173

1 Answers1

1

Udev:

Pass the environment variable as:

RUN+="/home/some/script/location/script.sh DEVNAME=$env{DEVNAME}"

and in the script script.sh parse the $@ variable for the device name as:

if [[ "$@" =~ (DEVNAME=/dev/sd.?) ]] ; then
__DEVNAME="${BASH_REMATCH[1]}"
__DEVNAME="${__DEVNAME#*=}" ; fi

You should then have device names e.g. /dev/sda in the $__DEVNAME variable.

Bash:

Install jq with:

sudo apt install jq

To find the device partition and mount point:

For partitions:

sudo lsblk -o NAME -J /dev/sda | jq -r '.blockdevices | .[].children | .[] | .name'

For mountpoint:

__TMPFILE="$(mktemp)"
sudo lsblk -p -o NAME,MOUNTPOINT -J /dev/sda | jq -r '.blockdevices | .[].children | .[] | "declare -A __MOUNTS[\(.name)]=\"\(.mountpoint)\""' > "$__TMPFILE"
source $__TMPFILE 
echo "Your mount point for sda1 is ${__MOUNTS[sda1]}"
rusty
  • 16,327