Simple Shell Script – File if-then-else


An annoyance with one of my Raspbery Pi computers is that the two USB weather stations it is connected to sometimes lose USB connectivty and appear on a different file handle. The USB port (either /dev/ttyUSB0 or /dev/ttyUSB1 then re-enuermates on a different file handle in the /dev folder.

Aside from fixing the issue in the firmware or kernel on the Pi (being investigated), a temporary fix is to restart the Pi when /dev/ttyUSB2 appears.


The soultion used is to have a script that checks if a new USB file handle appears and then reboot if that happens. We also need to check every five minutes if this happens because the weather station sends reports every 10 minutes and we need to ensure that it continues to do that in time.

So, that means a cron job and a shell script and here they are …

Shell Script (

Here’s the script in full:


 if [ -e "$USB0" ] && [ -e "$USB1" ]
  echo "$TIMENOW: $USB0 and $USB1 found"
  echo "$TIMENOW: $USB0 and $USB1 found" >> $LOGFILE
  echo "$TIMENOW: Exit normally"
  echo "$TIMENOW: Exit normally" >> $LOGFILE
  exit 0
# If get to here check for others
 if [ -e "$USB2" ] || [ -e "$USB3 ]
  echo "$TIMENOW: $USB2 or $USB3 found"
  echo "$TIMENOW: $USB2 or $USB3 found" >> $LOGFILE
  echo "$TIMENOW: USB re-numerated - reboot required"
  echo "$TIMENOW: USB re-numerated - reboot required" >> $LOGFILE

A log file is also included as that’s a useful diagnostic tool – don’t forget to use logrotate to chop it from time to time. The key bit is to do a shell if using -e to see if the file handle to the USB device is still there. As there are two USB devices to worry about (two file handles), use a logical or to ensure they are both there. Otherwise, something is broken so then do a reboot having logged that fact to the log file for later review.

Right, that takes care of the checking, now the cron job.

Cron Job

I set this to run as a root cron job (crontab -e to put this in your cron table for root). This ensures no problems with permissions and also means that root is rebooting and not anyone else.

#check every 5 mins if USB 0 or USB 1 get re-enumerated
#if USB0 or 1 disappears reboot to resync
*/5 * * * * /home/pi/cgi-bin/

That should get around the problem until a patch is available for the loss of USB enumeration.