3

I have Linux image that on boot, needs to execute a script that will be located on a plugged in thumbdrive. Here is what I have.

mkdir /mnt/usb
mount /dev/sda1 /mnt/usb
cd /mnt/usb/DMS
cp script.sh /
chmod +x /script.sh
/bin/sh /script.sh

This script is added late in the sysvinit scripts. It works with most drives, however, some drives take a while to get recognized. That means my script will fail, because /dev/sda1 isn't available yet.

How do I modify this shell script to perform a while/wait on the device, with a timeout if none is ever found.

Pseudo code:

counter = 1
while /dev/sda1 not present
   sleep 100
   counter++
   if counter is 50
      exit # no drive ever found
   endif
endwhile

# do stuff with plugged in drive, mount it, whatever

How do I perform something like this in a shell script?

2

Translating you pseudo-code directly into shell get

#!/bin/sh
counter=0

while [ ! -e /dev/sda1 ]; do
    sleep 100
    counter=$((counter + 1))
    if [ $counter -ge 50 ]; then
        exit
    fi
done

Optionally you can change -e /dev/sda1 to -b /dev/sda1 to check for block device.

3
  • Why would I want to check for a block device, instead of just using -e?
    – Paul Knopf
    Sep 29 '16 at 16:44
  • This is necessary primarily for elaborate scripts that get argument from command line and want to ensure that they deal with block device not just ordinary file. Sep 29 '16 at 17:09
  • NOTE: Not all USB sticks are mountable using this block device. I have come across some that in your example you'd be mounting as /dev/sda (i.e. no partition table).
    – mdpc
    Sep 29 '16 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.