18 Tar Command Examples in Linux

The Linux “tar” stands for tape archive, which is used by a large number of Linux/Unix system administrators to deal with tape drive backup in Linux.

The tar command in Linux is used to rip a collection of files and directories into a highly compressed archive file commonly called tarball or tar, gzip, and bzip in Linux.

The tar is the most widely used command to create compressed archive files that can be moved easily from one disk to another disk or machine to machine.

tar - A Linux Archiving Utility
tar – A Linux Archiving Utility

In this article, we will be going to review and discuss various tar command examples including how to create archive files using (tar, tar.gz, and tar.bz2) compression, how to extract archive files, extract a single file, view the content of the file, verify a file, add files or directories to the existing archive file, estimate the size of tar archive file, etc.

The main purpose of this guide is to provide various tar command examples that might be helpful for you to understand and become an expert in tar archive manipulation.

1. Creating a Tar Archive File

The below example of the tar command will create a tar archive file tecmint-17-11-2023.tar for a directory /home/tecmint in the current working directory.

See the example of the tar command in action.

tar -cvf tecmint-17-11-2023.tar /home/tecmint/
Create Tar Archive File
Create a Tar Archive File

Let’s discuss each option used in the above tar command.

  • c – Creates a new .tar archive file.
  • v – Verbosely show the .tar file progress.
  • f – File name type of the archive file.

2. Creating a Tar Archive with Compression

To create a compressed archive file, we use the option 'z' (compress the archive using gzip). For example, the command below will generate a compressed file named 'MyImages-17-11-2023.tar.gz' for the directory ‘/home/MyImages‘. (Note: 'tar.gz' and 'tgz' are interchangeable terms).

tar cvzf MyImages-17-11-2023.tar.gz /home/tecmint/MyImages
OR
tar cvzf MyImages-17-11-2023.tgz /home/tecmint/MyImages
Create a Compressed Tar Archive
Create a Compressed Tar Archive

3. Creating a tar.bz2 File in Linux

The bz2 feature compresses and creates an archive file that is smaller in size compared to gzip. However, the bz2 compression method requires more time for both compression and decompression, whereas gzip is faster in both processes.

To create a highly compressed new tar archive named Phpfiles-org.tar.bz2 by bundling all files and subdirectories within the /home/php directory, use the -j option, which instructs tar to utilize the bzip2 compression algorithm, resulting in a smaller file size for efficient storage and transfer.

Note: tar.bz2 and tbz are similar terms, both referring to tb2.

tar cvfj Phpfiles-org.tar.bz2 /home/tecmint/php
OR
tar cvfj Phpfiles-org.tar.tbz /home/tecmint/php
OR 
tar cvfj Phpfiles-org.tar.tb2 /home/tecmint/php
Create a tar.bz2 file Linux
Create a tar.bz2 file Linux

4. Extracting a Tar Archive

To untar or extract a tar file, simply execute the following command using the 'x' option (extract). For instance, the command below will untar the file named ‘tecmint-17-11-2023.tar‘ in the present working directory.

tar -xvf tecmint-17-11-2023.tar

If you want to untar in a different directory then use option -C (specified directory).

tar -xvf tecmint-17-11-2023.tar -C /home/tecmint/

5. Extracting a Compressed tar.gz Archive

To extract the contents of a compressed tar archive file named “MyImages-17-11-2023.tar.gz“, use the following command.

tar -xvf MyImages-17-11-2023.tar.gz

If you would like to extract in a different directory, just use the option -C, which will extract the files into the specified directory as shown.

tar -xvf MyImages-17-11-2023.tar.gz -C /home/tecmint/

6. Extracting a tar.bz2 Archive

To uncompress the highly compressed tar.bz2 file, simply use the following command, which will untar all the files from the archive file.

tar -xvf Phpfiles-org.tar.bz2

7. Listing Contents of tar Archive

To list or view the contents of the tar archive file, simply run the following command with the -t option (list content), which will display a detailed list of files and directories contained within the ‘tecmint-17-11-2023.tar‘ archive.

tar -tvf tecmint-17-11-2023.tar
View Tar Contents Without Extracting
View Tar Contents Without Extracting

8. Viewing Contents of tar.gz Archive

The following command will display a detailed list of files and directories contained within the “MyImages-17-11-2023.tar.gz” archive.

tar -tvf MyImages-17-11-2023.tar.gz
View Tar.gz Contents Without Extracting
View Tar.gz Contents Without Extracting

9. Printing Contents of tar.bz2 Archive

The following command provides an overview of the contents within the “Phpfiles-org.tar.bz2” archive without extracting the files.

tar -tvf Phpfiles-org.tar.bz2
View Tar Contents Without Extracting
View Tar Contents Without Extracting

10. Extracting a Single File from an Archive

To extract a single file named wp-cron.php from the archive Phpfiles-org.tar.bz2, use the following command. Make sure to provide the correct path to the file you wish to extract.

tar -xvf Phpfiles-org.tar.bz2 home/tecmint/php/wp-cron.php
Extract File From Tar Archive
Extract File From Tar Archive

11. Extracting Multiple Files from an Archive

To extract or untar multiple files from tar, tar.gz, and tar.bz2 archive files, use the following command, which will extract files from the specified archive files.

tar -xvf tecmint-17-11-2023.tar "file1" "file2" 
tar -zxvf MyImages-17-11-2023.tar.gz "file1" "file2" 
tar -jxvf Phpfiles-org.tar.bz2 "file1" "file2"

12. Extract a Group of Files Using Wildcard in Linux

To extract a group of files we use wildcard-based extracting. For example, to extract a group of all files whose pattern begins with .php from a tar, tar.gz, and tar.bz2 archive files, use:

tar -xvf Phpfiles-org.tar --wildcards '*.php'
tar -zxvf Phpfiles-org.tar.gz --wildcards '*.php'
tar -jxvf Phpfiles-org.tar.bz2 --wildcards '*.php'

13. Appending Files to an Existing Archive

To add files or directories to the existing tar, tar.gz, and tar.bz2 archive files, use the option -r, which will add the files to an existing archive file.

tar -rvf tecmint-14-09-12.tar xyz.txt
tar -rvf MyImages-14-09-12.tar.gz xyz.txt
tar -rvf Phpfiles-org.tar.bz2 xyz.txt

14. Verifying a Tar Archive File

The following command will display a detailed list of files and directories contained within the specified archive file, allowing you to visually verify the archive’s contents. If the archive is corrupted or incomplete, this verification process may reveal errors during the listing.

tar -tvf Phpfiles-org.tar.bz2

15. Checking Tar Archive File Size

To check the size of any tar, tar.gz, and tar.bz2 archive file, use the following command, which will display the size of the archive file in Kilobytes (KB).

tar -czf - tecmint-14-09-12.tar xyz.txt | wc -c
tar -czf - MyImages-14-09-12.tar.gz xyz.txt | wc -c
tar -czf - Phpfiles-org.tar.bz2 xyz.txt | wc -c

16. Excluding Files When Creating a Tar Archive

To exclude certain files and directories while creating a tar archive file, you can use the following command with the --exclude an option that will exclude files and directories when creating the tar archive file as shown.

tar --exclude='file1.txt' -zcvf backup.tar.gz /home/tecmint
tar --exclude='/home/tecmint/uploads' -zcvf backup.tar.gz /home/tecmint

In the above command, we excluded file ‘file1.txt‘ and ‘uploads‘ directory from the /home/tecmint folder.

To exclude files with specific file extensions (.txt) when creating a tar archive file, use:

tar --exclude='*.txt' -zcvf backup.tar.gz /home/tecmint

17. Removing Files From a Tar Archive

The following tar command will delete a file or directory from an already created tar file using the --delete option, as shown.

tar --delete -f backup.tar.gz file1.txt
tar --delete -f backup.tar.gz '/home/tecmint/uploads'

18. Extracing File Extension From a Tar Archive

The following tar command will only extract files with the specific extension .png from the tar archive file using the --wildcards option as shown.

tar -xvf backup.tar.gz --wildcards '*.png'

19. Tar Command Usage and Options

Understanding the following various options and usage patterns of the ‘tar‘ command is essential for efficient file archiving, compression, and extraction.

  • -c – create an archive file.
  • -x – extract an archive file.
  • -v – show the progress of the archive file.
  • -f – filename of the archive file.
  • -t – viewing the content of the archive file.
  • -u – archives and adds to an existing archive file.
  • -j – filter the archive through bzip2.
  • -z – filter the archive through gzip.
  • -r – append or update files or directories to the existing archive files.
  • -W – Verify an archive file.
  • -A – concatenates the archive files.
  • --wildcards – Specify patterns in the UNIX tar command.
  • --exclude – excludes files and directories when creating the archive.
  • --delete – remove the file and directory from the archive.

That’s it for now, hope the above tar command examples are enough for you to learn, and for more information please use the man tar command.

# man tar

If you are looking to split any large tar archive file into multiple parts or blocks, just go through this article:

If we’ve missed any examples please do share with us via the comment box and please don’t forget to share this article with your friends. This is the best way to say thanks…..

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

100 Comments

Leave a Reply
  1. Although I’ll remember the command later when I’m finished with other more important tasks. The guides so far are a good way to at least understand what the commands do.

    Reply
  2. Why do some of the `tar` commands shown above have the `-` in front of the options and other times it does not? It’s very confusing.

    Reply
    • In theory, you can have multiple options like:

      tar -c -z -f 
      tar -czf
      tar -zfc
      

      All of them are the same, but for those that are not a shorthand then they need to be typed in full such as this one then you need to type that option and separate it with a space for other options and so on

      tar --exclude 
      

      Weird though or maybe I wasn’t paying attention that sometimes we just forget to mention things and get others confused.

      Reply
  3. Working with the ‘tar‘ commands has become a daily routine for me now, because of your tutorial.

    Thank you very much and keep up the good work.

    Reply
  4. I wonder why you are calling Linux “tar“, tar is not part of Linux (Linux is a kernel) else it is part of the GNU project then you should call it: GNU tar otherwise you are confusing people.

    Reply
    • Thanks for the tutorial.

      We run Linux, the Puppy UpupBB +23 distribution. Our BackUp Routine in BASH script runs very well, but we want more “Progress” info for the user.

      We call “tar” from “BASH” this way :

      TAROPT="-c -z --checkpoint=1000" 
      tar ${TAROPT} -f ${lcPupSaveNameTrg} ${lcPupSaveNameSrc}
      

      We want to direct the progress “checkpoint” info into a text file, which can be displayed during the “tar” run.

      Any ideas? Any other approaches?

      Reply
  5. The wildcard is not working for me, it given an error called unmatched even when content is available in tar.

    e.g. content in work.tar.gz
             task/log/sum.log
    
    tar -zxvf  work.tar.gz --wildcards '*.log' , returns nothing but an error i.e. "UNMATCHED ."
    
    Reply
  6. There are a few errors in the article, such as “begin with .php” instead of “ended with .php” also several truncated commands and mixed-mashed command and switches which might mess up on some distribution. for example the .flv extract is nowhere specified on command line, you might mean “video directory” not *.flv. i counted several other errors, this article seriously needed polish. (I’ve posted this comment erroneously on the split article, sorry)

    Reply
  7. Can you also Pplease include tar with --exclude options, which is really helpful if you have to take entire OS backup excluding /usr, /var, etc.

    Reply
  8. It was really good example demonstration of using the tar command. However, I faced an issue after the creation of tar. I created a tar on a UNIX server and downloaded it into my windows.

    To my shock, after unziping (using 7-zip) the files inside tar (all txt files) where encrypted. How do I control the encryption while creating a tar?

    This is not the case when I use -xf cmd in the UNIX server.

    Why this encryption of data in UNIX while creating tar?

    –need help

    Reply
    • @Mohammed,

      The tar command never encrypt data or files during creation. It just compress the files into one single format i.e. tar.gz or tar.bz2. May I know how you created tar file in Unix server?

      Reply
      • Thanks so much for your post and help Mr. Ravi. I am seeing the same problem, so I think I know what he means. I tar’ed a folder structure on Centos, then moved the tar file to Ubuntu, when I untarred it, all the FILES in all the subfolders were themselves individual tarred files (all files .gz extension instead of the original .jpg extension for example).

        It means that for a folder structure with 10,000 files, in many subfolders, all 10,000 files in subfolders are now individual tar files, and I need to untar 10,000 files? No files in any of the subfolders exist in their original form, they have all been tar’ed to individual tar files. It is unbelievable.

        His question, if I am understanding him, is how to control the tar during tarring so it does NOT tar each individual file in each subfolder as an individual tar file? Under what conditions would anyone want this anyway? Hard to believe in 2018 I am having this kind of basic problem.

        Reply
  9. In this sentence “The tar is most widely used command to create compressed archive files and that can be moved easily from one disk to “anther” disk or machine to machine.”
    anther should be another.

    And thanks a lot for this tutorial.

    Reply
  10. Thanks for posting the information.

    It would be good if you could address the following in this page.

    1) Missing word – In this article we will going to review – ‘be’ is missing between ‘we’ and ‘going’ words
    2) Missing word – that might be helpful you – ‘for’ is missing between ‘helpful’ and ‘you’ words
    3) Sentence Correction – Let’s discuss the each option we have used in the above command for creating tar archive file.
    Correction: Let’s discuss each option that we have used in the above command for creating a tar archive file.
    4) Not required: The following example of command – ‘of’ is not needed
    5) Missing word: If you want untar in a different – ‘to’ is missing between ‘want’ and ‘untar’
    6) Correction: To list the content of tar archive file – ‘content’ should be ‘contents’ (Replace ‘content’ with ‘contents’ at appropriate location)
    7) Correction: to a existing compressed tar.gz – ‘a’ should be ‘an’
    8) Correction: If we do try will get tbe following error – ‘tbe’ should be ‘the’
    9) Spelling: ‘archvie’ should be ‘archive’
    10) Spelling: ‘patters’ should be ‘patterns’

    Reply
  11. Very nice, and now the second most important one is missing, namely: how to create split tar files into blocks of certain size.

    Anyway it helped me on my way.

    Greetings

    Reply
    • @Ferdinant,

      Thanks for finding it helpful, and also thanks for telling about that missing topic “how to create split tar files into blocks of certain size“, we will surely write on this topic and publish it by next week, till then stay tuned to TecMint.com

      Reply
  12. While extracting a particular file from the tarball, just giving a file name doesn’t work. You need to give the path of the file within the tarball.
    For example: I have taken a backup of my home directory called “/home/aziz” and it contains test1 and test2 files.

    $ tar -xvf /tmp/aziz.tar test1 — This command does not work while extracting a particular called test1
    $ tar -xvf /tmp/aziz.tar home/aziz/test1 — This command works while extracting a file called test1
    OR
    $ tar –extract –file=/tmp/aziz.tar home/aziz/test1

    Reply
  13. I think on on example 5 and 6 for untaring, -z and -b flags respectively are missing. But anyway thanks for this great tutorial.

    Reply
  14. I’ve got this bookmarked! It’s really helpful – thanks for posting this. I refer to it constantly when I’m SSHing and moving WordPress installations around!

    Reply
  15. Hi Ravi,
    I am trying to create tar file at AIX server using the below command:
    tar cvf temp.tar temp/
    but its just giving me tar: and create 0 byte tar file.
    I tried diffrent options like tar -cvf, tar cf, tar -cf, temp/,temp, complete path but for all I m getting same reposne.
    Please help :(

    Reply
  16. Good read, useful information . I also would like to understand how we can overwrite the file in the directories if already exist.

    Reply
  17. Note to the author:

    some of the filename is you tar examples look like adult photos to me (e.g. Miley**photo101203.flv). Just want to let you know in case that was not on purpose…

    Thanks for the helpful tutorial.

    Reply
    • @Franklin,
      What a finding….:) even I don’t know that I’ve used such images in my tar command examples. Actually I handle one large photo site in our media company. I think I tried those commands on that server and taken those images as example for tar command…..

      Reply
  18. Hi,
    Plz guide
    I want to fetch the file without extracting(need to paramatrize further )
    tar -Otvf TarFile –wildcards “*.tar.gz” or tar -tvf TarFile –wildcards ‘*.tar.gz’

    Reply
  19. hello ravi, thanks for the important stuff which u have shared with us..i am new to the linux and now only i am learning i want your support to get good knowledge in linux. if Any notes please send me to my mail id

    Reply
    • Dear Ravi, it’s not possible for me to send out emails to individual email id’s, better you subscribe to our email updates to receive such usefull stuff directly in your mailbox..

      Reply
  20. Hi..

    I want to create .tar.gz file.
    For that I used following command
    tar -czvf example.tar.gz /home/username/Desktop/Test
    I want only tar.gz file for my Test directory.
    But It creates directory structure like
    /home/username/Desktop/Test/ and all content inside Test directory in my tar.gz file.
    and I dont want “/home/username/Desktop/” directories in my tar.gz
    How to do this ? Please help me.

    Thanks in advanced.

    Reply
      • Thanks Ravi ..Thanks for quick reply .. Its working ..
        But If I extract example.tar.gz by right click on the file it displays example directory. But this is not happening with command line.
        If I use tar -xzf command for extract the file it displays all content in my example.tar.gz on target directory but insted of that I want example directory first and all content should be inside it.
        same as like how right click and extract works.

        Can you please help me ?
        Your help is very important for me.

        Thanks in advanced !

        Reply
          • If I put this command then it is showing

            tar: /home/prashant/Desktop/abc/example: Cannot open: No such file or directory
            tar: Error is not recoverable: exiting now

            The example directory is not exist

  21. Hi,

    Thanks for this post, it’s very well written and useful. i have a question…

    Do you know if it Is it OK to add files to a new tar archive that are already zipped (with gzip) prior to archiving? If I were to subsequently gzip the new tar archive, does that create any problems?

    In other words, would this be OK:

    tar -czvf example.tar.gz inputfile1.gz inputfile2.gz

    If I were to ‘untar’ and gunzip example.tar.gz (e.g. tar -xzvf example.tar.gz), would inputfile1 and inputfile2 be outputed as .gz or will they be gunzipped too? I’m worried double zipping might cause files to be corrupted.

    Many thanks, SImit

    Reply
  22. Hi Ravi ,
    I want to tar 10TB of data on tape drive , size of tape drive is 3 TB & using ultrium 5 .Can please specify the command which will help me take this on tape drive .

    Thanks on advance .

    Reply
    • The /dev/st0 is the default tape drive device name in Linux. So, to take tar backup of data on tape drive, you need to first rewind the tape using the following command.

      # mt -f /dev/st0 rewind
      

      Now backup data onto tape drive. For example, here I am taking backup of /data directory.

      # tar -czf /dev/st0 /data
      
      Reply
      • if my data is already .gz extention with total data size is 2.9 TB then can we take full data on 3 TB drive with below command or only 1.5 tB data will come on tape tape drive .

        tar -cvf
        or we should use tar – czf also any compression need to set on tape
        I using ultrium 5 , Hp data 3TB tape

        Pls help me on this

        Thanks in advance .

        Reply
  23. Hi Ravi,

    I am getting the following error message while trying to execute:
    tar -xvf public_html-14-09-12.tar -C /home/public_html/videos/

    Error message:
    File -C not present in the archive.
    File /home/public_html/videos/ not present in the archive.

    Can you please let me know what I am doing wrong here.
    Thanks in advance.

    Reply
  24. Thanks for great information but can you help me to tar the following

    /etc
    /home/root
    /usr/local
    /var/www
    /var/lib/mysql

    /backup/mybackup.tgz

    Reply
  25. Really useful Ravi and all.

    Like it is possible to Add a file to existing archive, it is possible to subtract a file from archive. man page indicates –delete.

    Example:
    tar -vf abcd.tar –delete path/of/file/in/archive/fileName

    Reply
  26. Very helpful article. Thanks for writing and sharing.

    I’ll check whether ‘z’ and ‘j’ switches for tar.gz and tar.bz2 are needed in the following commands, respectively:

    tar -xvf thumbnails-14-09-12.tar.gz

    tar -xvf videos-14-09-12.tar.bz2

    Reply
  27. My english not good pls excuse me, my ? is
    I want take daily backup and incremental backup but i don’t want more than 10 days backup file pls write cmd

    Reply
  28. Is there a way to resume a tar extract for a large file which was interupted due to script time out from the apache webserver?

    Reply
    • The tar command has options to exclude certain files. For example to exclude file ‘abc’ and ‘xyz’ you can use use the command as follows.

      $ tar -zcvf /home/tecmint.tar.gz --exclude='abc' --exclude='xyz' /home/tecmint
      
      Reply
      • Any way to exclude a folder or subfoler or file with tar itself.

        You have mentioned a option to exclude a file, not folder.

        Please correct it..

        Reply
  29. Don’t you need to add the “j” option to extract the bzipped tar file in example 6? I get errors when I don’t.

    Thanks for the all the examples. I wish more were included in manpages.

    Reply
    • Some versions of tar will detect the compression type and will automatically decompress it with the correct program (gzip or bzip2). Others will always assume it’s a regular, uncompressed tar file unless you pass it a “z” or “j” option. Some older versions of GNU tar even used the “I” (capital i) instead of “j” for bzip2 compression, and this is mentioned in the man page. The most portable method (I believe) is to decompress the file and pipe it directly to tar for extraction/listing:

      zcat archive.tgz | tar -xf –
      bzcat archive.tbz | tar -xf –

      Reply
  30. Number 18 does not do what you say it does. You say that it displays the size of an archive file in kilobytes, but what it actually does is creates a new gzip-compressed archive file (to an unnamed pipe) containing a single file (the archive file that you are supposedly “checking”) and displays the size of that new archive file in bytes (not in kilobytes).

    Here’s an easier and faster way to display the size of an archive file (or any other type of file) in kilobytes:

    ls -lk archive.tar
    ls -lk archive.tar.gz
    ls -lk archive.tar.bz2

    (The -k option is not standard but is supported by at least the Linux and BSD versions of ls.)

    Reply
    • That is handy, and often times faster than cp -r. Taking it one step further…

      tar -cf – dir | ssh user@remotehost “cd /newparent ; tar xvf -”

      rsync is faster keeping directories in sync, but tar is much faster the first time, especially with lots of small files.

      or to go the other way, and clone a directory from remote to local:
      ssh user@remotehost “cd /parent ; tar cf – dir” | tar xf –

      Reply
  31. The examples in section 13 won’t work as you suggest.
    You haven’t escaped the spaces in the filenames, so tar will try to add three files:
    “file”, “1”, “file” (again) and “2”.
    I suggest changing the example to use “file1” and “file2”.

    Reply
      • Dear Ayush,

        You can include additional files to an already created tar archive, just use the following command example to add or append files to any existing tar file.

        # $ tar rvf tecmint.tar newfile
        
        Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.