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]'

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]'

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.


A dirty quick loop doing it:

# 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
  • 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.