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"
Related videos on Youtube
Author by
Arun Reddy
Updated on September 18, 2022Comments
-
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 about 10 yearsDepends on your system. If you use
systemd
, you can write audev
rule usingSYSTEMD_WANTS
... It's documented inman systemd.device
. -
Admin about 10 yearsThe simplest solution would be to let your script do the mounting. What is causing the mounting now?
-
-
Arun Reddy about 10 yearsThis 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 over 3 yearsYou should use the
wait
command instead of thesleep
command.