suffa
suffa

Reputation: 3796

How to check for usb device with if statement in bash

I'm attempting to create an automated bash script that fills up a file with urandom in the unit's flash storage. I can manually use all of the commands to make this happen, but I'm trying to create a script and having difficulty figuring out how to check for the usb device. I know that it will be either sda1 or sdb1, but not sure if the code below is sufficient ...? Thanks! Below, is the code:

if /dev/sda1
then
         mount -t vfat /dev/sda1 /media/usbkey
else
         mount -t vfat /dev/sdb1 /media/usbkey
fi

Upvotes: 5

Views: 15558

Answers (2)

Matt H
Matt H

Reputation: 6532

The way I script mountable drives is to first put a file on the drive, e.g. "Iamthemountabledrive.txt", then check for the existence of that file. If it isn't there, then I mount the drive. I use this technique to make sure an audio server is mounted for a 5 radio station network, checking every minute in case there is a network interrupt event.

testfile="/dev/usbdrive/Iamthedrive.txt"
if [ -e "$testfile" ]
then
  echo "drive is mounted."
fi

Upvotes: 7

Diego Torres Milano
Diego Torres Milano

Reputation: 69198

You can mount by label or UUID and hence reduce the complexity of your script. For example if your flash storage has label MYLABEL (you can set and display VFAT labels using mtools' mlabel):

$ sudo mount LABEL=MYLABEL /media/usbkey

Upvotes: 6

Related Questions