How to XZ a directory with TAR using maximum compression?

With a recent GNU tar on bash or derived shell:

XZ_OPT=-9 tar cJf tarfile.tar.xz directory

tar's lowercase j switch uses bzip, uppercase J switch uses xz.

The XZ_OPT environment variable lets you set xz options that cannot be passed via calling applications such as tar.

This is now maximal.

See man xz for other options you can set (-e/--extreme might give you some additional compression benefit for some datasets).

XZ_OPT=-e9 tar cJf tarfile.tar.xz directory

Assuming xz honors the standard set of commandline flags - including compression level flags, you could try:

tar -cf - foo/ | xz -9 -c - > foo.tar.xz 

XZ_OPT=-9e tar cJf tarfile.tar.xz directory

is even better than

XZ_OPT=-9 tar cJf tarfile.tar.xz directory