Search code examples
syntaxtarmacos-monterey

Excluding specific directory in tar using --exclude


Imagine the following dir structure:

tartest> find .
.
./node_modules
./foo
./foo/node_modules
./foo/foo.js

Is there a way to exclude the top-level node_modules but not the one under foo using only tar (not a find/xargs solution).

I would have thought specifying the excluded directory using ./node_modules would work but

tartest> tar cvfz ../foo.tar.gz  --exclude='./node_modules' .
a .
a ./foo
a ./foo/foo.js

Solution

  • tar cvfz ../foo.tar.gz  --exclude='^./node_modules' .
    

    since --exclude takes a pattern. It remains to be seen if the '^' as beginning-of-line match is valid for your version of tar.