Search code examples
linuxbashredhatmountsles

on linux, how do I list only mounted removable media / device?


I know we can list all mounted devices using the mount command. or even the df command.

But how can we know if the listed device is removable or not, such as USB, CMROM, External Hardisk, etc?

For this question, we can start with how to do it on SUSE or RedHat.

Thanks!


Solution

  • After thinking about this a bit more, the way to determine if a drive is removable is to check whether the contents of:

    /sys/block/sdX/removable
    

    Is set to 0 - non-removable or 1 - removable. You can get the list of mounted drives (presuming the form /dev/sdX where X is a, b, c, etc..) and then loop over the devices checking the contents of the removable file.

    For bash using Process-Substitution to feed a while loop to loop over the device names removing the trailing partition digits and only taking unique devices you could do:

    #!/bin/bash
    
    while read -r name; do
      if [ "$(<${name/dev/sys\/block}/removable)" -eq "1" ]; then 
        echo "$name - removable"
      else
        echo "$name - non-removable"
      fi
    done < <(awk '/^\/dev\/sd/ {sub(/[0-9]+$/,"",$1); print $1}' /proc/mounts | uniq)
    

    Which will list all devices and whether they are removable. For example, running the script with a flash drive inserted (/dev/sdc) and my normal hard drive (/dev/sdb), you would receive:

    $ bash list-removable.sh
    /dev/sdb - non-removable
    /dev/sdc - removable
    

    There are probably many other ways to do it.