Tar is a useful utility that allows you to archive one of more files in Linux. You can also use it to compress one or more files, or directories into a tar.gz file. It is commonly used for data archival and backup in organizations. In this article, we will look at how to tar a file in Linux. We will cover different use cases for tar utility that might be helpful to you.
How to Tar a File in Linux
Let us look at the different scenarios to tar a file in Linux. Here is the syntax of tar command
$ tar [options] tar_file_name files/directories to be compressed
In the above line, tar command needs to be followed by one or more options, the file name of archive that needs to be created and a space separated list of files & directories that you want to archive/compress.
Open terminal and run the following command to tar a file in linux
$ tar -zcvf file.tar.gz /path/to/file
Let us look at the options in detail
- c – create an archive
- v – verbose meaning show progress
- f – filename is specified to be used
- z – archive using gzip
For example, here is the tar command to compress a single file /home/ubuntu/test.txt
$ tar -zcvf test.tar.gz /home/ubuntu/test.txt
Please note: If you run the tar command without specifying the tar filename you will get the error message “cowardly refusing to create an empty archive”. This is a common mistake many people do and the error message is confusing so it becomes difficult to fix it.
Also read : How to Upgrade to PHP 7.4 in Ubuntu
How to Tar multiple files
You can tar multiple files by simply listing their paths one after the other as shown below
$ sudo tar -zcvf test.tar.gz /home/ubuntu/test1.txt /etc/test2.txt /var/lib/test.txt
Also read : How to List all services using systemctl
How to tar a directory
Here is the command to tar an entire directory or folder
$ sudo tar -zcvf test.tar.gz /home/ubuntu/files
Also read : How to Setup FTP Server in Ubuntu
How to tar multiple directories
You can tar multiple directories by listing their paths one after the other in a space-separated format.
$ sudo tar -zcvf test.tar.gz /home/ubuntu/files1 /etc/files2 /var/lib/files3
Also read : How to Redirect 403 to 404 in NGINX
How to use bzip compression instead of gzip
By default, tar command uses gzip compression to archive data. If you want to use bzip compression instead, just use -j option instead of -z and change the file extension of tar file as .tar.bz2
$ sudo tar -cvjf test.tar.bz2 /home/ubuntu/test.txt
How to view contents of tar file
Here is the command to list the contents of your tar.gz file, using -t option
$ sudo tar -ztvf test.tar.gz $ sudo tar -jtvf test.tar.bz2
Also read : How to configure X-Frame-Options in Apache
How to Extract a tar file
Here is the command to extract a tar file
$ sudo tar -xzvf test.tar.gz $ sudo tar -xjvf test.tar.bz2
As you can see, it is very easy to use tar command and it is widely used for data compression and archival.