Find the answer to your Linux question:
Results 1 to 5 of 5
Hi, I made this hacky code, any suggestion to improve it? Code: for DEVS in $(ls -r /dev/sd[a-z] |cut -d"/" -f3); do for REMOVABLE in $(udevadm info -a -p /sys/block/$DEVS ...
  1. #1
    Just Joined! playerum's Avatar
    Join Date
    Aug 2010
    Posts
    22

    Get the removable devices

    Hi,

    I made this hacky code, any suggestion to improve it?

    Code:
    for DEVS in $(ls -r /dev/sd[a-z] |cut -d"/" -f3); do
    for REMOVABLE in $(udevadm info -a -p /sys/block/$DEVS | grep "ATTR{removable}==\"1\""); do
    DEVICE=/dev/$(echo $DEVS)1
    done
    done
    echo "$DEVICE
    I need only the firt removable device and the output must be:
    /dev/sde1, e.g.

  2. #2
    Linux Guru
    Join Date
    May 2011
    Posts
    1,842
    you just need a break to break out of the loop:
    Code:
    for DEVS in $(ls -r /dev/sd[a-z] |cut -d"/" -f3); do
      for REMOVABLE in $(udevadm info -a -p /sys/block/$DEVS | grep "ATTR{removable}==\"1\""); do
        DEVICE=/dev/$(echo $DEVS)1
        break
      done
    done
    echo "$DEVICE"
    However, that would return, for example, /dev/sda1, even if /dev/sda1 (the first partition) did not exist. You might want to put a check in there for the partition first. Something like:

    Code:
    for DEVS in $(ls -r /dev/sd[a-z] |cut -d"/" -f3); do
      for REMOVABLE in $(udevadm info -a -p /sys/block/$DEVS | grep "ATTR{removable}==\"1\""); do
        DEVICE=/dev/$(echo $DEVS)1
        if [ -b $DEVICE ]; then
          echo partition for /dev/$DEVS found
          break
        else
          unset DEVICE
        fi
      done
    done
    echo "$DEVICE"

  3. #3
    Just Joined! playerum's Avatar
    Join Date
    Aug 2010
    Posts
    22
    I'll make some tests and post a feedback.

    Tanks for now.

  4. #4
    Just Joined! playerum's Avatar
    Join Date
    Aug 2010
    Posts
    22
    one month later...

    Man,
    It works! Took me the whole day, but it works!

    Code:
    for devs in $(ls -d /sys/block/sd[a-z] | tr "@" " " | cut -d"/" -f4); do
      for rems in $(udevadm info -a -p /sys/block/$devs | grep ATTR{removable}==\"1\"); do
        SIZEDEV="$(udevadm info -a -p /sys/block/$devs | grep ATTR{size}=="\"" | cut -d"\"" -f2)"
        if [[ $SIZEDEV -gt 0 ]]; then
          DEVICE=/dev/$(echo $devs)1
        fi
      done
    done
    echo "$DEVICE"
    * If there is more than one removable device it takes the last, but i only use one, so this is what i need.

    Again, tanks atreyu, you helped me a lot!

  5. #5
    Linux Guru
    Join Date
    May 2011
    Posts
    1,842
    np - glad it works!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...