MacOS – List All Files in USB device from /Volumes Shell Script

macosterminalusb

To clear things up I have setup folder actions on my mac for whenever a USB device is plugged into my mac it will run a shell script.

When I list all files in the Directory /Volumes i get

$ ls -a
.       ..      .DS_Store   MobileBackups   Storage     WED

What I want to do is list all folders and files located in WED or any USB that pops up, so therefore excluding the directories

.       ..      .DS_Store   MobileBackups   Storage

Leaving me with

WED

What i have for the script so far is:

GLOBIGNORE='/Volumes/MobileBackups*':'/Volumes/Storage*'
find '/Volumes' >> /Users/Brett/dev/USBLOGS/LogUSB.txt

I have tried multiple different ways but it still ends up listing every single file in the /Volumes directory.

Any help would be greatly appreciated. Thanks, Brett

Additionally, it is MAC OS X El Capitan

Best Answer

Since you only want find to act on USB block devices the following is an example of using information reported by System Profiler to get the Mount Point of any attached and mounted USB block device. By doing it this way it doesn't matter what other mount points exist under /Volumes nor does it matter what the USB block device name is as it's ascertained from System Profiler not the ls command.

I've modified the code, once again, removing the compound command line as it not likely it would be run that way anyway and is easier to maintain in script form while adding the ability to handle spaces in the label name of the USB block device.

By temporarily changing the Internal Field Separator $IFS, adding IFS=$'\n' to the script will ignore the space(s) as a separator in the output of grep when passed to find. So as not to mess with any code in the rest of your script I fist get the state of $IFS and then rest it afterwards.

In a bash script:

#!/bin/bash

_ifs="$IFS"
IFS=$'\n'
for p in $(system_profiler SPUSBDataType | grep -oE '/Volumes/.*$'); do
    if [ -n "$p" ]; then
        find "$p"/*
    fi
done >> filename.txt 
IFS="$_ifs"

The system_profiler SPUSBDataType outputs info on the USB Bus and pipes it through grep to get /Volumes/$whatever e.g. /Volumes/USB Drive using -oE for the '/Volumes/.*$' which outputs /Volumes/ and everything after it to the end of the line, thus '/Volumes/.*$' will translate the fully qualified pathname of the mount point of any mounted USB block devices. So whatever the USB block device is mounted as, it's assigned to $p (I picked "p" for path) and when used with find I added the /* after it so it would not output the dotfiles. The if block is there to avoid any output if no USB block devices are mounted.