tar – How to Tar Files Only, No Directories

tar

I can probably write a shell script to find files only, then pass the list to tar, but I am wondering whether there already is a built-in feature in tar that allows doing just that, in a single command line?

For example, I found the --no-recursion switch, but when I do:

tar --no-recursion -cvf mydir.tar mydir

It only archives the names of the entries in the directory (including subdirectories!), but it doesn't archive any files.

I also tried:

 tar --no-recursion -cvf mydir.tar mydir/*

But while it archives files only, it also archives the names of the subdirectories.

Is there a way to tell tar files only, no directories?

Best Answer

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 {} +
Related Question