tar files only, no directories

When you want to use find with tar, the best way is to use cpio instead of tar. cpio can write tar archives and is designed to take the list of files to archive from stdin.

find mydir -maxdepth 1 -type f -print0 | cpio -o -H ustar -0 > mydir.tar

Using find and cpio is a more unix-y approach in that you let find do the file selection with all the power that it has, and let cpio do the archiving. It is worth learning this simple use of cpio, as you find it easy to solve problems you bang your ahead against when trying tar.


As camh points out, the previous command had a small problem in that given too many file names, it would execute more than once, with later invocations silently wiping out the previous runs. Since we're not compressing too, we can append instead of overwrite:

find mydir -maxdepth 1 -type f -print0 | xargs -0 tar Avf mydir.tar
find mydir -maxdepth 1 -type f -exec tar Avf mydir.tar {} +

Iocnarz's answer of using tar's --null and -T options works as well. If you have cpio installed, camh's answer using it is also fine. And if you have zsh and don't mind using it for a command, Gilles's answer using a zsh glob (*(.)) seems the most straightforward.


The key was the -maxdepth option. Final answer, dealing with spaces appropriately:

find mydir -maxdepth 1 -type f -print0 | xargs -0 tar cvf mydir.tar

This should also work:

find mydir -maxdepth 1 -type f -exec tar cvf mydir.tar {} +

I'm not sure I understand your requirements. If you want to store the regular files in mydir but not its subdirectories, the easiest way is to use zsh, where matching regular files only is the simple matter of using the . glob qualifier:

tar cf mydir.tar mydir/*(.)

Tags:

Tar