Linux – Bash scripting parted for GPT

bashgptlinuxpartedpartitioning

Using Bash & Python scripts in Ubuntu 12.04, we are delivering a disk image to customers as a file (generated by dd). Once dd’d to the new disk, we resize the partition to fit the disk. Now that we are using GPT disks, I need to provide a new non-interactive, non-X script.

The problem is parted generates an interactive message:

Error: The backup GPT table is not at the end of the disk, as it
should be. This might mean that another operating system believes the
disk is smaller. Fix, by moving the backup to the end (and removing
the old backup)? Fix/Ignore/Cancel?

But using -s or -m switch with parted I am unable to get it to resize the disk and fix the location of the backup GPT. I can’t echo an “F” into the command either:

echo "F" > parted  /dev/sda resize 2 0% 100%
parted  /dev/sda resize 2 0% 100%
parted -m /dev/sda resize 2 100%
parted -s /dev/sda resize 2 100%

And so forth. gdisk and sgdisk don’t seem to be able to resize. gparted works fine but it’s X of course and not allowed.

From the CLI I can squelch the interactive message by running in backticks:

`parted -s /dev/sda rm 2`  ( succeeded with error)
`parted -s /dev/sda mkpart primary 100%` ( fails because the backup GPT was not moved)

So I need the special “move GPT backup” service offered in the interactive message, and only offered there, but I need to run non-interactively.

Best Answer

Dru's approach will probably work, although I've not tested it. Two other approaches are to use a combination of sgdisk and parted, or to use sgdisk in a more complex way. Specifically, you could do either of:

  • Use sgdisk -e to move the backup partition table data to the end of the disk, followed by parted {device-file} resize... to resize the partition. Using two utilities rather than one is a bit inelegant, but it should work.
  • Use sgdisk -e {device-file} to move the backup partition table data to the end of the disk, followed by sgdisk -d... to delete the partition and then sgdisk -n... to create a new partition in its place. You can probably combine these into just two or maybe even just one call to sgdisk. One caveat is that this approach will change the GUID value for the partition. If it's important that it remain the same, you'd have to extract that data and reset the GUID value -- or given that you're starting from a known image, you could store the GUID value as part of your script and reset it without first extracting it.

Note that I've not tested either of these approaches, so I can't guarantee them any more than I can guarantee Dru's method.