bash - test if disk is unpartitioned

5

1

I'm currently working on a DIY network storage which aggregates free disk space using mhddfs.

Now what I want is, for example given a hotswap bay, when I insert a brand new unpartitioned disk, I wish to automatically partition the disk using a bash script and mount the new mhddfs partition.

The same situation occurs if the server is turned off, new disk gets inserted and the server is turned on again.

So the question is: How can i detect an unpartitioned disk using a bash script?

The question also includes that there should be no false detections. e.g. if an encrypted disk is inserted, it shouldn't be automatically repartitioned and formated - This point is the main interest in the question.

John Doe

Posted 2012-09-07T16:43:41.790

Reputation: 269

If the whole disk is encrypted, you may not be able to tell.

– Kamil Maciorowski – 2018-04-25T13:02:12.750

I think that the answer will involve scripting dd to peek at the partition table. Maybe someone familiar with the partition table data would like to weigh in with a scripted answer?

– zero2cx – 2012-09-07T17:09:18.313

Answers

3

One option to perform the checking and partitioning is the parted command. To get partition information on all disk block devices in the system, in "human-readable" format:

/sbin/parted -l

or, in "machine-readable" format, use:

/sbin/parted -lm

You will need to parse the output in the to determine if the disk has a valid partition table.

Then, use something like:

/sbin/parted <device> --script mkpart primary 1 -- -1

to make a single partition using the whole disk. The syntax on mkpart subcommand is from memory and I do not have a system with an available disk to verify it is correct

Yedric

Posted 2012-09-07T16:43:41.790

Reputation: 649

3

Here's a way I'm using for backups.

if [ $(/sbin/sfdisk -d ${DEV} 2>&1) == "" ]; then echo "Device not partitioned"; fi

where ${DEV} is the device you are interrogating (Best ran from a udev script.)

Spenser Gilliland

Posted 2012-09-07T16:43:41.790

Reputation: 31

0

I really liked the answer posted on stackoverflow which suggests:

parted --script

Like:

parted --script /dev/sdb print

Felipe Alvarez

Posted 2012-09-07T16:43:41.790

Reputation: 1 666

0

Check out the gpart command (guess PC-type hard disk partitions, needs root). Another question is: how is your script started, when a new disk is inserted?

ott--

Posted 2012-09-07T16:43:41.790

Reputation: 1 911

0

I assume you're doing this on a Linux kernel.

Use fdisk or sfdisk from the util-linux package:

fdisk -l /path/to/disk

or:

sfdisk -l /path/to/disk

to list current partition table.

Linux detects available partitions, so looking in the /dev/disk directories might be enough for your needs.

Thor

Posted 2012-09-07T16:43:41.790

Reputation: 5 178