Tar Command Examples in Linux

Tar Command in Linux and its examples:

The command tar stands for tape archive which is used to rip a collection of files and directories into highly compressed archive file called tarball.

1. Create a tar file:

# tar -cvf example.tar /root/test/

The above command will create a tar file named “example.tar” for the directory /root/test/ in the current working directory.

Here,

c – to creates a new tar file.

v – for verbos

f – file name type of the archive file

 

2. Create a tar.gz file:

# tar cvzf example.tar.gz /root/documents

The above command will create an example.tar.gz file for the /root/documents directory.

Where,

z – is used for gzip.

 

3. Untar a tar file:

# tar -xvf example.tar -C /root/documents/
# tar -xvzf example.tar.gz -C /root/documents/

The above commands will untar the example.tar and example.tar.gz files in /root/documents/ directory.

Where, 

x – is used to extract.

C – is used to specify the path.

 

4. List content of a tar file:

# tar -tvf example.tar
# tar -tvf example.tar.gz

The above command will list the content of the example.tar and example.tar.gz files.

Where,

t – is used to list the content.

 

5. Extract a single file from a tar file:

# tar -xvf example.tar test1.txt 
OR 
# tar --extract --file=example.tar test1.txt

# tar -xvzf example.tar.gz test2.txt
# tar -xvjf example.tar.bz2 test3.txt

The above command will extract the single files (test1.txt, text2.txt and test3.txt) from those tar files.

Where,

j – is used for the highly compressed tar files (.bz2)

 

6. Extract multiple files from a tar file:

# tar -xvzf example.tar.gz "test1.txt" "test2.txt"

The above command will extract the test1.txt and test2.txt files from the example.tar.gz tar file.

 

7. Append files or directories to a tar file:

# tar -rvf example.tar test5.txt

The above command will append the file test5.txt to the existing example.tar file.

Where,

r – is used to append.

Note: We cannot append any file or directory to tar.gz and tar.bz2 files.

 

8. How to verify a tar file?

# tar tvfW example.tar

The above command will verify the example.tar file.

Where,

W – is used to verify.

Note: We cannot verify tar.gz and tar.bz2 files.

That’s it in this article, hope you enjoyed it. Please share it across if you think it’s good.

Leave a Reply

Your email address will not be published. Required fields are marked *