How to create an APFS-formated volume on an external drive using Terminal

apfscommand line

I want to create a case-sensitive encrypted APFS formatted Volume on my external drive using only the CLI. I had a look at man diskutil already but this doesn't seem to have all the details required. So I'm kind of stuck right now, any help appreciated.

Best Answer

Use newfs_apfs(8) to format a partition with a new APFS filesystem, i.e. to create a new APFS container. For example:

sudo newfs_apfs -e -v "My APFS Container" disk0s2

With diskutil, I find that just entering the diskutil command itself and reading the help that it outputs is more accessible than the manpage. You can do this for subcommands, too; eraseVolume is the subcommand you're interested in, and you can enter diskutil eraseVolume to get help on how to use this subcommand.

The eraseVolume subcommand will overwrite a partiton with a particular filesystem — it will use the relevant newfs_* command behind the scenes, thus serving as a general interface to all of the newfs_* commands — or leave the partition unformatted. diskutil listFilesystems will show you the valid filesystems you can specify. For example:

diskutil eraseVolume APFSX "My APFS Container" disk0s2

Alternatively, if you wish to reformat a partition that has an existing filesystem, keeping the same filesystem type and filesystem label / volume name, you can use the reformat subcommand instead. For example, if disk0s2 is already a case-sensitive APFS container with the name My APFS Container that may already contain data or is broken, and you just want a clean slate, then the above eraseVolume command is equivalent to:

diskutil reformat disk0s2

(Note that diskutil needn't be run with sudo.)