How to tar (compress) files up, excluding certain files or directories

If you’ve ever been making a backup of an entire Linux system, or maybe just a number of folders but there were certain folders or files that you didn’t want to have in the backup or zip file, then Look no further than this Quick Tip!

First, change to the folder you want to zip, or back up and make sure you have permissions to access all of the files within the folder. For example, if the folder is / (root) then you will need superuser permissions so don’t forget to run tar with the sudo command!

cd /folder_to_backup

Next, you want to run the tar command to create the archive/zip file. The usual z (gzip compression), c (create), v (verbose), f (file) flags are used, but note that they come at the latter part of the command line. This placement seems important across differing distributions of Linux.

You can see that using the –exclude option we can specify the folders and/or files to exclude, you can have as many –exclude options as you need. Note how the path is prefixed with a period (denoting the current directory). This is important because the exclude flag matches text patterns, not actual filenames, and the pattern starts with ./ – You can also use other regular expressions. For example you can use a wildcard such as file* to match any file or folder name beginning with the word file.

tar --exclude='./folder_to_exclude' --exclude='./myfolder/file.txt' -zcvf /backup/filename.tgz .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.