The “tar” command stands for “tape archive” and the basic Unix command to archive files. By default the command will save the archive in a
.tar file but it can also save it to a gzip file with the
.gz extension. The tar command typically is available in most Linux distro.
There are also some alternatives such as the
gunzip which specially handles the .gz file and
unzip which is for the .zip extension. These alternatives may not always be available so check the distro package manager if they can be installed as an additional command.
General syntax for
tar [OPTIONS] [FILES]...
Create an archive
tar -cf [archive] [file]
-f options create a new archive file with the files specified to be archived.
Example: Archiving the new1.txt and new2.txt files into the example.tar archive without compression.
List contents of an archive
tar -tf [archive]
-t option allows you to view the contents of the archive file without decompressing it.
Example: Listing the contents of the example.tar file.
Create a Gzip archive
tar czf [archive.tar.gz] [file]
-z option with the
tar command to create a new archive using gzip compression.
Example: Creating a tar file named example.tar.gz and zipping new1.txt and new2.txt into it.
Extract an archive
tar -xf [archive]
-x option allows you to extract files from an archive to your current working directory. It is also possible to extract certain files by specifying the file names.
Example: Extracting the archive example.tar, which contains the text files new1 and new2.
Add files to an existing archive
tar -rf [archive] [file_to_add]
To append a file or directory to an existing tar archive file, use the
-r option. This option adds files to the end of an archive.
Example: Adding the new1.txt file to the example.tar archive.
tar -Af [archive] [archive_to_be_added]
-A option to append files from one archive to another. It adds files to another archive’s end.
Example: Merging the files of the file1.tar archive into the file2.tar archive.
Delete a file from an archive
tar --delete -f [archive] [file]
--delete option allows you to delete a file or multiple files from an archive at once.
Example: Removing the new1.txt file from the example.tar archive.
Find differences between archive and file
tar -df [archive] [file]
To determine the differences between an archive and a file, use the
Example: Finding the difference between the example.tar archive and the new1.txt file.
Add only new files to the archive
tar -uf [archive] [files_to_add]
-u option to add files that are newer than the file in the archive. The newer files do not overwrite the older ones in the archive.
Example: Appending all new files in text format from the current directory to the example.tar archive.
Extract archive to a specific directory
tar -xf [archive] -C [dirpath]
-C option allows you to extract the archive to a certain directory by specifying the destination path.
Example: Extracting files from the example.tar archive to the dir/test folder.