Open In App

How to Exclude Files and Directories When Creating a tar.gz File

Improve
Improve
Like Article
Like
Save
Share
Report

GNU tar is a type of archiving program that is designed to store multiple files into a single file and to manipulate such archives. The archive can be either a regular file or a device that can be located either locally or on a remote machine. 

How to Exclude Files and Directories When Creating a tar.gz File

Step 1: First we need to create multiple files and directories for demonstration.

Step 2: With the help of mkdir we need to create a parent directory.

mkdir targfg

 

Step 3: Create multiple files and directories inside the parent directory.

touch file1 file2 file3
mkdir dir1 dir2 dir3

 

 

 

Using –exclude option

While creating a tar file, if we need to remove any file or directory in the tar archive queue then we need to use the –exclude option in which we can assign any file_name or directory_name that we want to exclude.

tar -cvzf tar_file_name –exclude=file/directory file_location

tar -cvzf backup.tar.gz –exclude=demo1.txt targfg/

 

Using an exclude file

1. First, we need to create a file named as “excludefile”.

2. Then, we need to write the file_name, and directory_name which we want to exclude.

3. We can write the command as 

tar -cvzf tar_file_name -X exclude_file_path main_file_path

tar -cvzf gfgbackup.tar.gz -X targfg/excludefile.txt targfg/

 

 

 

Exclude multiple files and directories when creating a tar file

Creating tar file when passing file and directory names with exclude option

1. tar -cvzf gfgbackup.tar.gz –exclude={file1,file3,dir1,dir2}  targfg/ 

 

 

Exclude file with a specific extension

With the help of the tar command, we can also exclude the file with a specific extension when creating an archive file.

1. Excluding specific files as .txt files 

tar -cvzf gfgbackup.tar.gz –exclude=*.txt targfg/

 

 

Other several options

1. –exclude-backups:

This option excludes all the backup and lock files when creating a tar archive file.

2. –exclude-caches:

This option excludes the contents of directories containing CACHEDIR.TAG, except for the tag file itself.

3. –exclude-tag=FILE:

This option excludes the content of directories containing FILE.

4. –exclude-vcs:

This option excludes version control system directories.

5. –exclude-vcs-ignore:

This option excludes patterns from VCs ignore files.

Conclusion

The above article demonstrates the basic definition of tar, and tar options while creating a tar archive file. It also describes the usage of exclude option and how we can take exclude option in modes of operation like excluding multiple files, excluding directories, or excluding files with specific file extensions.


Last Updated : 02 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads