An archive file is nothing but a collection of files and directories stored in one file. Please note that by default the archive file is not compressed. A compressed file uses less disk space.
This blog page explains how to compress, list, and extract files using the tar command on Linux or Unix-like systems.
Compress files with tar at the shell prompt
For archiving files at the shell prompt, use the tar command as follows. The syntax is:
tar -cvf fileName.tar file1 file2 file3
tar -cvf fileName.tar dir1 dir2 dir3
tar -cvf fileName.tar file1 dir1
Where,
- c : Create a new archive
- v : Verbose output
- f : Use given archive file or device
- C: Change to directory DIR
Linux compress files with tar
For example, the c option requires creating the archive, the v option requests the verbose operation, and the f option takes an argument that sets the name of the archive to operate upon. The following command, written in the traditional style, instructs tar to store all files from the directory /tmp/test/ into the archive file test.tar verbosely listing the files being archived:
$ tar -cvf test.tar -C / tmp/test/
Sample outputs:
/tmp/test/1.txt /tmp/test/ps.txt /tmp/test/alok.log
The following adds file named /etc/resolv.conf, /etc/hosts, and /home/alok/Documents directory:
$ tar -cvf backup.tar /etc/resolv.conf /etc/hosts /home/alok/Documents
Compressing Files at the Shell Prompt
For compressing files you need to use the compression utilities:
- bzip2 – tar.bz2 file
- gzip – tar.gz file
- zip – tar.zip file
To compress the tar file with gzip pass the -z option, run:
$ tar -cvzf docs.tar.gz /home/alok/Documents/
To compress the tar file with bzip2 pass the -j option, run:
$ tar -cvjf docs.tar.bz2 /home/alok/Documents/
To list the contents of a tar file, enter:
$ tar -tvf docs.tar
$ tar -tvzf docs.tar.gz
$ tar -tvjf docs.tar.bz2
To extract the contents of a tar file, enter:
$ tar -xvf docs.tar
$ tar -xvzf docs.tar.gz
$ tar -xvjf docs.tar.bz2
Where,
- t : List the contents of an archive
- x : Extract a tar archive
- z : Compress the tar file with gzip
- j : compress the tar file with bzip2
Conclusion
This page explained the basic syntax of tar, and I hope you learned how to compress files with the tar commands running on Linux, FreeBSD, OpenBSD, macOS, and Unix-like operating systems. The tar command has many more options. Hence, I suggest that you read the tar command help page here.