≡ Menu

Exclude certain files from tar file when creating backup?

The question – how to exclude certain files from my tar file when I am creating an archive of a backup of my file system? I need tar to ignore all readme.* files. Is there an option to do this?

The tar command is very useful to create an archive of a directory on Linux.

The command to recursively archive all files in the current directory and all sub-directories is as under:

tar -cvf backup.tar *

Now you want to exclude all readme.* files. To do this, you should use the following command:

tar -cvf backup.tar --exclude=readme.* *.*

The above command takes in as argument –exclude=pattern which says that the pattern that is passed in should be excluded when the archive is created. That pattern can be anything like *.txt, *.sql, *.gif, images.*, *images* etc.

If you have a lot of patterns that need to be excluded, you can create a text file with the patterns:

touch patterns.txt
vi patterns.txt

And then add all the patterns in the file one line at a time:

Once you have your patterns.txt file, you can pass it as an argument to tar:

tar -cvf backup.tar -X patterns.txt *.*

The above command will exclude all patterns in the patterns.txt file!

To exclude an entire directory, add that directory to the patterns file. For example, if you want to exclude /home/ewhathow/ from the archive, add that to the patterns.txt file, or use the following command:

tar -cvf backup.tar --exclude=/home/ewhathow *.*

Comments on this entry are closed.