Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 429
Basj Avatar asked Sep 15 '16 15:09

Basj


People also ask

How do I exclude a directory in tar?

You can exclude directories with --exclude for tar. To clarify, you can use full path for --exclude.

How do you exclude a directory?

We can exclude directories by using the help of “path“, “prune“, “o” and “print” switches with find command. The directory “bit” will be excluded from the find search!

What can you do with a Tar GZ file?

Tar GZ files are most commonly used for: Storing multiple files in one archive. Sending and receiving larger files in a compressed format. Compressing single files to store locally.

Does tar follow symlinks?

When reading from an archive, the ' --dereference ' (' -h ') option causes tar to follow an already-existing symbolic link when tar writes or reads a file named in the archive. Ordinarily, tar does not follow such a link, though it may remove the link before writing a new file.


1 Answers

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.

like image 185
Tim Avatar answered Sep 19 '22 13:09

Tim