parted
can print free space. Example (I chose a complicated one on purpose):
# parted /dev/sda unit s print free
[...]
Number Start End Size Type File system Flags
63s 2047s 1985s Free Space
1 2048s 4196351s 4194304s primary fat32 lba
4196352s 4198399s 2048s Free Space
2 4198400s 6295551s 2097152s primary ext2 boot
6295552s 6297599s 2048s Free Space
3 6297600s 27269119s 20971520s primary ext2
27269120s 27271167s 2048s Free Space
4 27271168s 31115263s 3844096s extended lba
5 27273216s 29192191s 1918976s logical ext2
6 29194240s 31115263s 1921024s logical ext2
31115264s 31116287s 1024s Free Space
As you can see this gives you directly the position and size of the partition you may be able to create, i.e. the very last line that says Free Space
. You could create a partition that starts at 31115264s and ends at 31116287s.
If it weren't for the pitfall that the extended partition isn't large enough!
But maybe you already use GPT where you do not suffer from such complications.
Grabbing the numbers should be easy enough.
function make_partition
{
parted -s "$1" unit s mkpart primary "$2" "$3"
}
make_partition /dev/sda `parted /dev/sda unit s print free | grep 'Free Space' | tail -n 1`
Or something similar. (Naturally you'd want to do some more sanity checks here.)
@swisscheese made a good comment in the other answer, I didn't know parted
offered parse friendly output. You might opt to use that instead. Example for grabbing the last largest free:
# parted -m /dev/sda unit s print free | grep 'free;' | sort -t : -k 4n -k 2n | tail -n 1
1:27269120s:27271167s:2048s:free;
Whether that's applicable for your situation (in my example, you couldn't create a partition there either, it's already full really) is something you have to figure out for yourself. :)