Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for usb device with if statement in bash

Tags:

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
like image 651
suffa Avatar asked Jan 03 '12 15:01

suffa


2 Answers

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
like image 128
Matt H Avatar answered Oct 20 '22 02:10

Matt H


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
like image 6
Diego Torres Milano Avatar answered Oct 20 '22 03:10

Diego Torres Milano