Basj
Basj

Reputation: 46493

Exclude directories from tar archive with a .tarignore file

In a similar way to .gitignore, is it possible to do that a .tarignore file in a subdirectory makes it excluded from archive when doing

tar cfjvh backup.tar.bz2 .

(I know the --exclude parameter of tar but here it's not what I want).

Upvotes: 8

Views: 9256

Answers (3)

McModknower
McModknower

Reputation: 141

I just found out that git has a tool to package the tracked files itself: git archive. Using that is probably the easiest way.

EDIT: If you want to make a package out of files / data that is not yet commited (but tracked), using tar -czf files.tar.gz $(git ls-files) works.

Upvotes: 8

Tim
Tim

Reputation: 4948

Using the --exclude-ignore=.tarignore option causes Tar to use .tarignore files in a similar way that git uses .gitignore files. Use the same syntax as you would usually use in .gitignore files, so if you want to ignore all sub-directories and files in a particular directory, add a .gitignore file with * to that directory. For example:

$ find dir
dir
dir/a
dir/b
dir/c
dir/dir1
dir/dir1/1a
dir/dir1/1b
dir/dir2
dir/dir2/2a
dir/dir2/2b
$ echo "*" > dir/dir1/.tarignore
$ tar -c --exclude-ignore=.tarignore -vjf archive.tar.bz2 dir
dir/
dir/a
dir/b
dir/c
dir/dir1/
dir/dir2/
dir/dir2/2a
dir/dir2/2b

If you want to ignore all directories that have an empty .tarignore file, take a look at the --exclude-tag-all=.tarignore option.

$ find dir
dir
dir/a
dir/b
dir/c
dir/dir1
dir/dir1/1a
dir/dir1/1b
dir/dir2
dir/dir2/2a
dir/dir2/2b
$ touch dir/dir1/.tarignore
$ tar -c --exclude-tag-all=.tarignore -vjf archive.tar.bz2 dir
tar: dir/dir1/: contains a cache directory tag .tarignore; directory not dumped
dir/
dir/a
dir/b
dir/c
dir/dir2/
dir/dir2/2a
dir/dir2/2b

Also take a look at the --exclude-tag= and --exclude-tag= options, which are variations which have slightly different behaviors.

Upvotes: 13

Inian
Inian

Reputation: 85653

You can do something like

$ COPYFILE_DISABLE=true tar -c --exclude-from=.tarignore -vzf archiveName.tar.gz

The breakdown:-

  • Reason for COPYFILE_DISABLE=trueis for making sure files starting with ._ are not included in the .tar file made. Enable it permanently adding export COPYFILE_DISABLE=true to ~/.bash_profile on your Mac if you frequently do tar operations.
  • –exclude-from=.tarignore: Ignore all files and folders listed in .tarignore

You can have the following content in your .tarignore, here is mine

$ cat .tarignore
.DS_Store
.git
.gitignore

Upvotes: 7

Related Questions