How do I create a tar file in alphabetical order?

Solution 1:

Slartibartfast is on the right track, but tar's default behaviour is to descend into directories, so you may get more than one copy of the same file included in the generated tar file. You can check by doing tar tf file.tar | sort The workaround is to include the --no-recursion option to tar. Also, you should be able to send in strange filenames by using the -print0 option to find, then using --null option to tar. The end result looks like this:

find paths -print0 | sort -z | tar cf tarfile.tar --no-recursion --null -T -

You can check the order in the tar file by using tar tsf tarfile.tar. Although you'll probably never need the -print0, -z, and --null options unless you know you're going to encounter a filename with a newline embedded in it, I've never tried it.

Solution 2:

The order of the files within the tar file does not really matter, since when the files are extracted, the filesystem will not preserve the order anyway.

There is no switch for this, but if you really wanted it, you could provide tar with a list of filenames in sorted order, and it would create the tar file with the order you give it.

% tar cf tarfile tmp/diff.txt src/hellow.c junkimage.IMG barry/thegroup
% tar tf tarfile
tmp/diff.txt
src/hellow.c
junkimage.IMG
barry/thegroup

Solution 3:

Assuming you don't have any files with newlines in the names:

find /source_directory -print | sort | tar -czf target.tgz -T -

If that doesn't work (never tried it, so I don't know of - means stdin for the -T argument):

find /source_directory -print | sort > /tmp/temporary_file_list
tar -czf target.tgz -T /tmp/temporary_file_list

Then there is the question of why. But sometimes it is easier not to ask.

Solution 4:

find . -depth -print0 | sort -z | pax -wvd0 > file.tar

Pax is sort of the POSIX successor to cpio and tar and kind of fuses the best aspects of both. It writes tar archives (ustar) by default. It also does automatic spanning and prompting for media and prints a summary when it's done.