In Linux systems, the most popular archiving tool is the GNU tar programmer (short for Tape Archiver). The Tar Command in Linux aids in creating, extracting, and listing archive contents and is directly accessible in the terminal.
The tool is straightforward and offers a wide range of advantageous choices for managing backups, compressing data, and extracting a raw installation.
This guide demonstrates the use of the Tar Command in Linux using examples and all of the available options.
- A system running Linux.
- Access to the command line/terminal.
- A file or files for testing the command.
Tar Command Syntax
The general syntax for the tar command is:
tar 'operation mode' 'options' 'archive' 'file' or 'location'
1: Which operation is performed on the files is indicated by the operation mode.
2: (Conception, exploitation, etc.) The command only permits and necessitates one activity.
3: Options are optional and change the operation mode. There is no restriction on the variety of choices.
4: The file name and extension are the archives.
5: A list of file names separated by spaces is used for extraction, compression, or wildcard matching.
The operations and options can be used in one of three syntax types:
1: Traditional style, clustered together without any dashes.
For example:
tar cfv <archive> <file(s) or location(s)>
2: UNIX short option style, using a single dash and clustered options:
tar -cfv <archive> <file(s) or location(s)>
Alternatively, a dash before each option:
tar -c -f -v <archive> <file(s) or location(s)>
3: GNU long-option style with a double-dash and a descriptive option name:
tar --create --file <archive> --verbose <file(s) or location(s)>
All three styles can be used in a single Tar Command in Linux.
Tar Command Options
The following table outlines the commonly used tar operations and options.
Command | Role | Description |
–create -c |
Operation | Creates a new archive. |
–list -t |
Operation | Lists an archive’s contents. |
–extract -x |
Operation | Extract one or more items from an archive. |
–append -r |
Operation | Appends files to an existing archive. |
–concatenate -A |
Operation | Appends archives to an existing archive. |
–compare –diff -d |
Operation | Compares archive members with files on the system. |
–delete | Operation | Deletes a member from the archive. |
–update -u |
Operation | Updates archive with new files only if they are not in the archive and are newer than existing files. |
–file=<archive> -f <archive> |
Option | Specifies the file. |
-C | Option | Changes the directory. |
–verbose -v |
Option | Shows the file tar works on while running. |
–wildcard | Option | Renders wildcard search options. |
–bzip2 -j |
Option | Read or write compressed archives through bzip2 format. |
–gzip -z |
Option | Read or write compressed archives through gzip format. |
–xz -J |
Option | Read or write compressed archives through xz format. |
Follow the examples in the next section to learn how to work with tar.
Tar Commands Example Commands
The criteria for the examples below are as follows:
1: make a directory called “tar examples” and go there:
cd tar examples and then run "mkdir tar examples"
2: Create the following directory, files in tar examples, and enter it:
cd files and mkdir files
3: Produce documents to fill the files directory:
open the file "0.100.txt"
Use: to get back to the parent directory.
cd.
All the examples below work from the tar examples directory.
1: Create an Archive
Depending on the type of archive, a certain syntax must be used. Use tar with the -c or —create command to generate an archive.
Establish a tar archive.
Create a tar archive, often known as a tarball, by using:
tar cf "archive name"
tar files or directories
As an illustration, backup the files directory:
files in tar cf format
Each file added to the archive is listed in the output. To see the newly created file, show the directory contents. the tar archive
files in tar cf format
Each file added to the archive is listed in the output. To see the newly created file, show the directory contents. the tar archive
ls –l
Create a tar.gz Compressed Archive
Add the -z option to create a compressed GNU zip (gzip) file:
tar czf <archive name>. tar.gz <file(s) or location(s)>
For example:
tar czf files.tar.gz files
The file size is smaller than a regular tarball file and the original directory.
Create tar.bz2 Compressed Archive
The bzip2 is a file compression program and an alternative to gzip.
To create a tar.bz2 file, add the -j tag:
tar cjf <archive name>. tar.bz2 <file(s) or location(s)>
For example:
tar cjf files.tar.bz2 files
The bzip2 has a greater compression rate and takes longer than gzip.
Create tar. xz Archive
Use the -J tag to compress archives in the tar.xz format:
tar cJf <archive name>.tar. xz <file(s) or location(s)>
For example:
tar cJf files.tar. xz files
2: Eliminate Files Following Creation
Use the —remove-files option at the end to delete the files from disc after archiving:
tar cf "archive" "file" "location" —remove-files
As an illustration, execute the following Tar Command in Linux to build a tar archive of the files directory and delete it from the disc:
files in tar cf format —remove-files
To ensure the procedure is successful, check the directory’s contents.
3: Taking from the Archive
The -x or — extract operation with tar is used to extract from an archive or compressed archive. The extra choices are based on the file type and the location where tar should extract the parts.
Taken from the tar archive
When extracting from a tar archive, the general syntax is:
Tar XF. Tar
The components are all extracted to the current directory by default when using tar. Add the -C option and the path to the command to specify where to extract the components:
xfC tar xfC.tar
Run the following command, for instance, to create the directory extracted tar and extract the files from files.tar.
tar xfC files.tar extracted tar and mkdir extracted tar
There is no confirmation message output by the command. Verify the directory’s contents to ensure that the components were correctly extracted.
Extract from tar.gz Archive
Use the -z option to extract a tar.gz file:
tar xzf .tar.gz
The command extracts the contents in the current directory. Add the -C option to specify the location:
tar xzfC .tar.gz
For example, create a new directory named extracted_gz and extract the files.tar.gz contents:
mkdir extracted_gz && tar xzfC files.tar.gz extracted_gz
The tar.gz compressed archives take the least time to extract when compared to other compression formats.
Extract from tar.bz2 Archive
To extract files from a tar.bz2 compressed archive into the current directory, use:
tar xjf .tar.bz2
Extract tar.bz2 archives into a specific directory with:
tar xjfC tar.bz2
For example, create a directory and extract the contents from files.tar.bz2:
mkdir extracted_bz2 && tar xjfC files.tar.bz2 extracted_bz2
Extract from tar. xz Archive
Add the -J option to extract from tar. xz compressed archives. The syntax to extract in the current directory is:
tar xJf .tar.xz
To extract the contents to a specific directory, use the -C option and add the path:
tar xJfC .tar. xz
As an example, create a directory and extract the files.tar. xz contents:
mkdir extracted_gz && tar xJfC files.tar. xz extracted_gz
The xz compression format is the middle ground between gz and bz2 when it comes to extraction time.
4: Rewrite Authority
When the names of files in the working directory and the archive have the same names, tar overwrite controls handle the situation.
1: These are the three potential overwrite actions:
Files in the working directory should be overwritten:
tar xf "archive", "optional file(s), or (locations)" —overwrite
2: Refrain from replacing files in the working directory:
tar xf "archive", "optional file(s), or (locations)" —keep-old-files
Tar does not extract the files if they already exist.
3: Only extract files if they are more recent than the ones already present.
tar xf "archive", "optional file(s), or (locations)" —keep-newer-files
Tar does not extract files if the working directory’s files are more recent or the same age.
5: List Archive Contents
Use the following command to list an archive’s contents:
tar tf <archive>
The option works for any file extension containing tar.
For example, list the files and directories in the files.tar archive:
tar tf files.tar.gz
The output lists all contents stored in the archive.
6: Find a File in an Archive
There are two ways to locate specific content using tar:
1: The -t option to list files in an archive is handy for locating specific files. Add the file name (or names) after the command:
tar tf <archive> <file(s)>
For example, to locate file50.txt in the files.tar.gz archive, run:
tar tf files.tar.gz file/file50.txt
The option requires knowing the possible path to the file.
2: Use the tar together with the grep command to filter the output:
tar tf <archive> | grep <file(s)>
For example:
tar tf files.tar.gz | grep file50.txt
The option doesn’t require knowing the possible path to the file.
7: Find Multiple Files in an Archive
Use the –wildcards option to match multiple file instances. For example:
tar tf files.tar.gz --wildcards file/files5*.txt
Apply wildcard matching when files have a similar name, or for filtering a certain file type.
8: Exclude Files When Creating an Archive
To exclude certain files from the archive during creation, add the following option:
tar cf <archive> --exclude='<pattern>' <files(s) or location(s)>
For example, create an archive from the files directory and exclude all .txt files:
tar cf files.tar --exclude='*.txt' files
List the archive contents:
tar tf files.tar
The output shows no .txt files, only the files directory in the archive.
9: Extract a Single File from the Archive
Avoid extracting the whole archive if you need one or several files.
To get a single file from an archive:
1: List the contents and check if the file exists:
tar tf files.tar | grep file100.txt
The output prints the path to the file needed for the next step.
2: Extract the specific file with:
tar xf files.tar files/file100.txt
The Tar Command in Linux only includes the specified file when creating the directory files. By adding the proper tag, repeat these procedures to extract a single file from compressed archives. For instance, to pull from a tar.gz file, use the -z option.
10: Verbose Option
The verbose option displays additional information after running a tar command. Add -v or –verbose to any operation to see the result.
For example, create a tar.gz file and add -v:
tar czfv files.tar.gz files
The output shows each file as it is added to the archive.
Some tar commands show additional information when you add the -v tag twice. For example, try to add files to an archive with -vv:
tar czfvv files.tar.gz files
The output prints a long listing format and looks similar to running the ls -l command.
11: Delete from Archive
To delete from the archive, locate the file you want to remove, for example:
tar tf files.tar | grep file100.txt
Then, remove the file using the –delete tag:
tar --delete -f files.tar files/file100.txt
The delete option does not work on compressed file formats.
12: Append Files to Archive
Append files to an existing archive using the -r tag. The syntax is:
tar rf <archive name>.tar <file(s) or location(s)>
For example, append the compressed files.tar.gz file to the files.tar archive:
tar rf files.tar files.tar.gz
Already compressed archives cannot be updated. So the syntax only works for tarball files.
13: Combine Archives
Use the –concatenate or -A option to combine multiple archives. The basic syntax is:
tar Af
As an example, copy the existing files.tar file using the cp command:
cp files.tar files_copy.tar
Next, concatenate the two archives:
tar Af files.tar files_copy.tar
To confirm the concatenation worked, check the file size.
14: Difference Between Archive and Files
To check the difference between an archive and files on disk, use the -d tag:
tar df
The command looks for identical items and contrasts them with the contents of the archive. The option ignores newly inserted files and only looks for existing files.
The steps below show how to use the -d, –diff, or –compare tag with tar:
1: Create a tar archive:
tar cf files.tar files
2: Compare the archive with the existing directory:
tar df files.tar
The output does not display anything, meaning there is no difference between the existing files.
3: Add text to an existing file in the files directory:
echo 'Hello' >> files/file0.txt
4: Compare the archive to the existing directory again:
tar df files.tar
This time, the report reveals variations in the size and modification time for a particular file. Comparing sheds light on any system modifications performed after the archive was created.
15: Update Files in the Archive
Update the existing files in the archive with a newer version from disk with the -u option:
tar uf
For example, update the files.tar archive with a changed text file:
tar uf files.tar files
Check the tar contents for the changed file:
tar tfv files.tar | grep files0.txt
The command updates the archive with changed files without any overwrites.
16: Modified Time
Tar offers various options to modify the file’s timestamp. Set a custom date when creating an archive by adding the –mtime option and providing a date:
tar cf --mtime=YYYY-MM-DD
For example, create an archive and set the date to January 1st, 1999:
tar cf files.tar files --mtime=1999-01-01
Alternatively, extract the files with the current date and time:
tar xf files.tar -m
A useful feature when working with time is filtering files modified after a specific date. For example, to extract files created after a date, use the –newer-mtime option and add the date:
tar xf --newer-mtime=YYYY-MM-DD
17: Permissions
There are two possible ways to control file permissions with tar when extracting an archive:
1: Preserve original permissions:
tar xf --preserve-permissions
The permissions are as stated in the file before archive creation.
2: Modify the permissions to the default umask value:
tar xf --no-same-permissions
The files take on the default Linux permissions.
18: File Ownership
Tar allows file ownership configuration. For example, to set the file owner when creating an archive, add the –owner and –group options and provide values for each:
tar cf --owner= --group=
The owner value represents the UID (User ID) while the group value is the GID (Group ID). To find these values for a user, run:
id
For example, create an archive and set the ownership to root:
tar cf files.tar files --owner=0 --group=0
Tar allows preserving the ownership when extracting from an archive. To do so, add the –same-owner option at the end:
tar xf --same-owner
19: Write to External Program
The –to-command option instructs tar to send each extracted file to the standard output for an external program. The basic syntax is:
tar xf --to-command=''
For example, extract the files.tar contents and pipe the file names as directories:
tar xf files.tar --to-command='mkdir $TAR_FILENAME'
Each extracted file is given its own directory, which the command creates. Visit the manual page for more details and a list of the available Linux environment variables.
20: Create Daily Backups
To automate daily backups, create a bash script and add the following lines:
tar czf backup-$(date +%Y%m%d). tar.gz files
find backup* -mtime +1 -delete
The find command looks for backup files older than one day, whereas the tar tool builds a compressed archive. For weekly or monthly backups, change the +1 parameter to +7 or +31, respectively.
Conclusion
You are familiar with how to use the Tar Command in Linux after reading this tutorial. There are, however, a number of additional options that are not covered in this guide. To learn everything there is to know about tar options, use the man command.
Read More:
- How To Use Mkdir Command To Make Or Create A Linux Directory?
- Create Symbolic Links In Linux: A Step-By-Step Guide
- Different Between Linux Server Vs Windows Server: Which One Is Right For You?
- How To Change File Permissions Recursively With Chmod In Linux?