views:

5874

answers:

6

I have a need to find all of the writable storage devices attached to a given machine, whether or not they are mounted.

The dopey way to do this would be to try every entry in /dev that corresponds to a writable devices (hd* and sd*).

Is there a better solution, or should I stick with this one?

+4  A: 

Use libsysfs, the recommended way to query the kernel about attached devices of all kinds.

David Schmitt
+2  A: 

Modern linux systems will normally only have entries in /dev for devices that exist, so going through hda* and sda* as you suggest would work fairly well.

Otherwise, there may be something in /proc you can use. From a quick look in there, I'd have said /proc/partitions looks like it could do what you need.

Mark Baker
+3  A: 

ls /sys/block

Mihai Limbășan
doesn't list partitions. I'm not sure whether that's what the original question wanted or not.
Mark Baker
I never knew about /sys/block - though it also lists devices that are not writable, like the DVD drive
warren
Indeed it doesn't list partitions - you can check the subdirectories though, looking for all subdirs holding at minimum files named "dev", "stat" and "uevent" and subdirs named "holders". DVDs are still storage class devices :)
Mihai Limbășan
moocha, why don't you expand your answer a bit?
SpoonMeiser
@warren - presumably /dev/dvd will just be an alias for a /dev/sd* or /dev/hd* device, so you would have had this problem anyway.
SpoonMeiser
A: 

libsysfs does look potentially useful, but not directly from a shell script. There's a program that comes with it called systool which will do what you want, though it may be easier to just look in /sys directly rather than using another program to do it for you.

Mark Baker
+2  A: 

/proc/partitions will list all the block devices and partitions that the system recognizes. You can then try using "file -s <device>" to determine what kind of filesystem is present on the partition, if any.

Steve Baker
This ommits CD/DVD drives for example (I know they're usually not writable)
pixelbeat
There's kind of a limit on what you can do from a shell. Most of the other suggestions that are higher rated either don't work from a shell, won't work unless dbus is running, or will list devices that aren't actually present/configured. This is just faster than checking all the /dev devices.
Steve Baker
+4  A: 

Using HAL (kernel 2.6.17 and up):


#! /bin/bash
hal-find-by-property --key volume.fsusage --string filesystem |
while read udi ; do
    # ignore optical discs
    if [[ "$(hal-get-property --udi $udi --key volume.is_disc)" == "false" ]]; then
        dev=$(hal-get-property --udi $udi --key block.device)   
        fs=$(hal-get-property --udi $udi --key volume.fstype) 
        echo $dev": "$fs
    fi 
done
ZungBang