1

So I am working a script that basically check if a disk has been added to the system, and if so, then do something with it (like format it or whatever).

So, the main question is...how do I list disks (or dev) that do NOT have any partitions?

I can list them with:

fdisk -l | grep -o '/dev/sd[a-z][0-5]'
/dev/sda1
/dev/sda2
/dev/sda5
/dev/sdb1

How can I list the disks that do not have any partition? I tried something like this:

# fdisk -l | grep -o '/dev/sd[a-z][^0-5]'
/dev/sda:
/dev/sdb:
/dev/sdc:

but I still get disks like sda and sdb which do have partitions. I jsut want to take sdc which is the only one that has no partition and is not being used on the system. Reason I want to do this is so I can put it on a bash script.

2

A dirty quick loop doing it:

#!/bin/bash
# get all disks into an array
disks=($(ls  /dev/sd* | grep -v '[0-9]')) 

# loop over disks in array
for i in $(echo ${disks[@]}); do
    # check if it has a partition
    diskcheck=$(ls ${i}* | grep '[0-9]')
    # if not, print it
    if [ -z "$diskcheck" ]; then
        echo $i
    fi
done
  • yes! thank you! I was looping through the array but I was not doing an echo on it, that explains it. Thank you so much! – user3311890 Sep 19 '18 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.