6

I have a bash script which has a line cd /run/media/Username/121C-E137/ this script is triggered as soon as the pen-drive is recognized by the CPU but this line should be executed only after the mounting process is complete. As of now what happens is this line is executed before the pen-drive is mounted and returns an error the directory is invalid.

2
  • Depends on your system. If you use systemd, you can write a udev rule using SYSTEMD_WANTS... It's documented in man systemd.device.
    – jasonwryan
    Apr 23, 2014 at 8:14
  • The simplest solution would be to let your script do the mounting. What is causing the mounting now? Apr 23, 2014 at 21:22

2 Answers 2

5

A simple solution would be to have the script periodically check for the directory, and only proceed once it's there:

PENDRIVE='/run/media/Username/121C-E137'
while [ ! -d "$PENDRIVE" ]; do
    sleep 10
done

cd $PENDRIVE
...
2
  • 1
    This sleep command is suspending the mounting as well the Pen-drive never gets mounted now until i comment the newly added lines in the script .
    – Arun Reddy
    Apr 23, 2014 at 12:06
  • You should use the wait command instead of the sleep command.
    – testter
    Sep 16, 2020 at 4:53
1

The following will check that the pendrive directory is mounted by checking if it appears in /proc/mounts

pendrive='/run/media/Username/121C-E137'
while ! grep -q -s "$pendrive" /proc/mounts; do
        sleep 10
done
cd "$pendrive"

If you need to account for the uncommon possibility mounts like ~/run/media/Username/121C-E137 that aren't what you want, then you could modify that to:

pendrive='/run/media/Username/121C-E137'
while ! grep -s "$pendrive" /proc/mounts | awk '{print $2}' | grep -q -s -x "$pendrive"; do
        sleep 10
done
cd "$pendrive"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .