How to make a bash script wait till a pendrive is mounted?

5,447

Solution 1

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
...

Solution 2

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"
Share:
5,447

Related videos on Youtube

Arun Reddy
Author by

Arun Reddy

Updated on September 18, 2022

Comments

  • Arun Reddy
    Arun Reddy over 1 year

    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.

    • Admin
      Admin about 10 years
      Depends on your system. If you use systemd, you can write a udev rule using SYSTEMD_WANTS... It's documented in man systemd.device.
    • Admin
      Admin about 10 years
      The simplest solution would be to let your script do the mounting. What is causing the mounting now?
  • Arun Reddy
    Arun Reddy about 10 years
    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 .
  • testter
    testter over 3 years
    You should use the wait command instead of the sleep command.