Monday, October 14, 2013

11 Tar Command Examples




1. Create tar Archive File
Following command will create a mytest.tar file for a directory "/home/anup/test".

[root@server ~]# tar -cvf mytest.tar /home/anup/test
Description of above options we have used to create .tar file.
c – Creates a new .tar archive file.
v – Verbosely show the .tar file progress.
f – File name type of the archive file. 

2. Create tar.gz Archive File 

To create tar.gz archive file we used option z. [Note: .tar.gz and .tgz both are similar]. 

[root@server ~]# tar -cvzf mytest.tar.gz /home/anup/test OR
[root@server ~]# tar -cvzf mytest.tgz /home/anup/test
3. Create tar.bz2 Archive File

To create highly compressed tar file we use option as j. [Note: tar.bz2 and tar.tbz is similar as tb2]

[root@server ~]# tar -cvjf mytest.tar.bz2 /home/anup/test OR

[root@server ~]# tar -cvjf mytest.tar.tbz /home/anup/test OR

[root@server ~]# tar -cvjf mytest.tar.tb2 /home/anup/test
 
4. Untar tar Archive File 

Untar files in Current Directory. 
[root@server ~]# tar -xvf mytest.tar

Untar files in specified Directory
[root@server ~]# tar -xvf mytest.tar -C /tmp/

5. Uncompress tar.gz Archive File

Following command will untar .tar.gz file at current location. If you want to untar in different directory then use -C option as we used in above command.

[root@server ~]# tar -xvf mytest.tar.gz

6. Uncompress tar.bz2 Archive File

[root@server ~]# tar -xvf mytest.tar.bz2

7. List Content of .tar / .tar.gz / .tar.bz2 Archive File

[root@server ~]# tar -tvf mytest.tar

[root@server ~]# tar -tvf mytest.tar.gz

[root@server ~]# tar -tvf mytest.tar.bz2

8. Untar Single file from .tar / .tar.gz / .tar.bz2 Archive File
 
[root@server ~]# tar -xvf mytest.tar test/mytextfile OR
[root@server ~]# tar -xvf --extract --file=mytest.tar test/mytextfile
 
[root@server ~]# tar -xvzf mytest.tar.gz test/mytextfile OR
[root@server ~]# tar -xvzf --extract --file=mytest.tar.gz test/mytextfile
 
[root@server ~]# tar -xvjf mytest.tar.bz2 test/mytextfile OR
[root@server ~]# tar -xvjf --extract --file=mytest.tar.bz2 test/mytextfile
 
9. Untar Multiple files from .tar, .tar.gz and .tar.bz2 Archive File
[root@server ~]# tar -xvf mytest.tar "test/mytextfile1" "test/mytextfile2”

[root@server ~]# tar -xvzf mytest.tar.gz "test/mytextfile1" 
"test/mytextfile2"
 
[root@server ~]# tar -xvjf mytest.tar.bz2 "test/mytextfile1" "test/mytextfile2"

10. Untar Single directory from .tar, .tar.gz and .tar.bz2 Archive File
 
[root@server ~]# tar -xvf mytest.tar test/directoryname

[root@server ~]# tar -xvf mytest.tar.gz test/directoryname

[root@server ~]# tar -xvf mytest.tar.bz2 test/directoryname

11. To see the content of a particular file in .tar / .tar.gz / .tar.bz2 archive without unzipping the contents
 
[root@server ~]# tar -xvf mytest.tar --to-command=cat test/mytextfile

[root@server ~]# tar -xvf mytest.tar.gz --to-command=cat test/mytextfile

[root@server ~]# tar -xvf mytest.tar.bz2 --to-command=cat test/mytextfile