1

On a backup process the program has to copy tar.gz file to a mounted USB flash drive. The program (nodeJS) uses API child_process.exec() to run the shell script. The function itself obtains the stdio.

So, using a shell script, how can I check whether the USBFlashDrive is disconnected/unplugged?

The device usually appears as sd[a-z]1 - please note the regex in the string.

Zanna
  • 72,312
Hairi
  • 153

3 Answers3

0

I don't know much about nodeJS (I am a C++ guy) but you can check the presence of drive in /dev/ folder.

When I plugged in my pen drive, I get file /dev/sdc. If I unplugged it then /dev/sdc vanishes .

Here is some more info about How to check if a file exists in a shell script

Zanna
  • 72,312
0

To check which USB disks are connected look in /dev/disk/by-path/

ls -l /dev/disk/by-path/*usb*  | grep -v "part" | awk '{print $NF}'|  awk -F "/" '{print $NF}' | sort

The output of previous command will list only usb disks.

grep -v "part" - excludes the partitions.

sdb
sdc

Then lsblk command can print some useful info like model and size.


#!/bin/bash
for usb in $(ls -l /dev/disk/by-path/*usb*  | grep -v "part" | awk '{print $NF}'|  awk -F "/" '{print $NF}')
  do
   lsblk  -n -d -o NAME,MODEL,VENDOR,SIZE,RM /dev/$usb
done


To check where the partitions of USB disks are mounted

#!/bin/bash
for usbp in $(ls -l /dev/disk/by-path/usb  | grep "part" | awk '{print $NF}'|  awk -F "/" '{print $NF}')
  do
   findmnt -rno TARGET /dev/$usbp
done
Zanna
  • 72,312
0

I suggest

lsusb

according to its author,

lsusb is a utility for displaying information about USB buses in the system and the devices connected to them.

An example:

hani@My-FRIEND:~$ lsusb
Bus 001 Device 002: ID 8087:8001 Intel Corp.  
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub  
Bus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub  
Bus 002 Device 005: ID 8087:07dc Intel Corp.   
Bus 002 Device 004: ID 04f2:b3a3 Chicony Electronics Co., Ltd   
Bus 002 Device 003: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller  
Bus 002 Device 007: ID 090c:1000 Silicon Motion, Inc. - Taiwan (formerly Feiya Technology Corp.) Flash Drive  
Bus 002 Device 002: ID 0458:0185 KYE Systems Corp. (Mouse Systems)   
Bus 002 Device 006: ID 1c4f:0002 SiGma Micro Keyboard TRACER Gamma   Ivory  
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

So as you see, the seventh line of the output shows details about the flash drive (USB drive) that is plugged in right now to the computer (via the USB port).

Zanna
  • 72,312
singrium
  • 7,320