[Linux] : How to exclude directory when using “tar” shell command

In day-to-day activities administrators needs to perform regular backups on their Linux servers. Being myself an administrator, i would recommended “tar”, the simple and the best tool. Backup doesn’t mean all the files and folders need to be backed up ! Sometimes we may have to exclude directories like template cache, log files, cache, temporarily created files, gallery directory etc., So in this article, we will see how to exclude certain directories and certain patterns even !

1. tar –exclude “directory”

Note: When excluding directories, make sure NOT to use the trailing slash(/) at the end of the directory name.

I have wasted much time in exploring this. So requesting you to not to waste time and follow the good procedure to get the work done soon.

Bad Practice :

tar -cvf backup.tar --exclude="public_html/template/cache/" public_html/

Good Practice :

tar -cvf backup.tar --exclude="public_html/template/cache" public_html/

2. tar –exclude Multiple directories

To exclude multiple directories you can either provide directories separately or by listing each directory seperated by comma and encased in {curly brackets}.

Method 1 :

tar -cvf backup.tar --exclude="public_html/template/cache" --exclude="public_html/images" public_html/

Method 2 :

tar -cvf backup.tar --exclude={"public_html/template/cache","public_html/images"} public_html/

3. tar –exclude directories from a File

List all the directories to be excluded into a file and use this list to exclude directories during tar.

Method 1 :

tar -cvf backup.tar -X exclude_directory.txt public_html/

Method 2 :

tar -cvf backup.tar --exclude-from=exclude_directory.txt public_html/

exclude_directory.txt Contains :


4. tar –exclude certain patterns

Sometimes we might find multiple pattern in different folders and we would not be interested only on that pattern. So here we see how to exclude particular pattern.

To exclude directory with particluar pattern :

tar -cvf backup.tar --exclude="log" --exclude="cache" public_heml/

To exclude files with patterns containing preceding and trailing characters :

tar -cvf backup.tar --exclude="*.log" --exclude="cache*" public_heml/

Updated on September 3, 2017

Was this article helpful?

Related Articles


  1. when excluded drectory contains subdirectories, this is still included into tar file

Leave a Comment