Exclude files from Tar Archive

Tar is a UNIX/Linux utility which is used to compress files for storage in an archive. When we tell tar to compress and create an archive of a directory, it will go ahead and include all the files in that directory.

Sometimes we may want to exclude a particular file from an archive. Tar allows use a convenient option to specify a file or files to exclude when making the archive. The tutorial below shows how we do a tar exclude file operation by using the command line.

Tar Exclude Example - Exclude a single file when using tar

The tar utility gives us a --exclude=filename option which we can use to list the file we want to exclude.

If we had the following files in a directory:

/home/arena/abc
/home/arena/logs
/home/arena/mail
/home/arena/foo.htm
/home/arena/bar.htm

If we wanted to exclude the file /home/arena/mail we would use the following command:

tar -cvzf backup.tar.gz --exclude='/home/arena/mail' /home/arena

The above command would create the archive just as normal, except that it would exclude the file /home/arena/mail from the archive.

Tar Exclude Example - Exclude multiple files when using tar

If we have a list of files which we want to exclude when we are creating an archive, we can list the names in a file and then tell tar to exclude those files.

Suppose we had the same files:

/home/arena/abc
/home/arena/logs
/home/arena/mail
/home/arena/foo.htm
/home/arena/bar.htm

And we wanted to exclude /home/arena/mail, /home/arena/logs and all files with a .htm extension. We would first place the names in a file like so:

We would have a file called something like exclude-list.txt and its contents would be:

logs
mail
*.htm

Then we would use the following command:

tar -cvzf backup.tar.gz -X exclude-list.txt /home/arena

Note that exclude-list.txt would be the path to the file which contains the names of the files to exclude. Tar would go ahead and read the files to get the names and patterns of files to exclude, then it would build the archive and exclude those files.

Using the above techniques when using the tar utility will allow you to have greater control over the files which are added to or excluded from your archives.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...