Resize a sparsebundle Disk Image in Terminal

I was trying to resize a sparsebundle disk image using Disk Utility and kept getting the error that the image resize had failed. The selected disk image could not be resized. Terminal to the rescue. The following command resized my disk image without any issues:

hdiutil resize -size XXXg /pathTo/diskimage.dmg

Change XXX to the size you would like, enter the path to your disk image Terminal may spit out some lines of “text” but you can ignore those. This process will resize the disk image but it has not expanded the container. Find the physical stores name (disk name) for your disk image either using the Disk Utility app or via the Terminal with the following command:

diskutil list

Once you have the correct disk name, eg. disk4s1, enter the following command into Terminal to expand the container:

diskutil apfs resizeContainer disk4s1 0

Terminal will show you the progress of the expansion. I found I had to unmount and then remount the disk image for the Finder to show the correct size, which you can also verify using Disk Utility.