31 October 2021

tar is a Unix/Linux command used to collect many files/directories into one archive file, often referred to as a tarball.
The name tar derived from "Tape ARchive" and its initial release is around January 1979.

I usually use this program to create compressed archive or extract files/directory from an archive.

Note: all example below could be execute in a container:

docker run -it  ubuntu /bin/bash

Create compressed archive

  1. Create a file and subdir folder example
    cd /tmp && mkdir test-compress && cd test-compress
    echo "Hello World!" > file1.txt
    (mkdir subdir && cd subdir && echo "Hello World! [2]" > file2.txt)
    
  2. Create compressed archive using tar
    tar -czvf archive.tar.gz file1.txt subdir
    
  3. List all files

    # ls -latr *
    -rw-r--r-- 1 root root   13 Oct 31 05:13 file1.txt
    -rw-r--r-- 1 root root  209 Oct 31 05:18 archive.tar.gz
    
    subdir:
    total 12
    -rw-r--r-- 1 root root   17 Oct 31 05:13 file2.txt
    drwxr-xr-x 3 root root 4096 Oct 31 05:18 ..
    drwxr-xr-x 2 root root 4096 Oct 31 05:18 .
    

Decompress and extract archive

  1. Starting from the last step of the previous example, create destination folder

    cd /tmp && mkdir test-decompress && cd test-decompress
    cp ../test-compress/archive.tar.gz .
    
  2. Decompress and extract archive using tar

    tar -xvf archive.tar.gz
    
  3. List all files:

    # ls -latr *
    -rw-r--r-- 1 root root   13 Oct 31 05:13 file1.txt
    -rw-r--r-- 1 root root  209 Oct 31 05:19 archive.tar.gz
    
    subdir:
    total 12
    -rw-r--r-- 1 root root   17 Oct 31 05:13 file2.txt
    drwxr-xr-x 2 root root 4096 Oct 31 05:18 .
    drwxr-xr-x 3 root root 4096 Oct 31 05:19 ..
    

As you can see the list all files show that tar command decompress and extract correctly and it also preserve file attributes, such as: name, timestamps, ownership, file-access permissions, and directory organization.

References