tar command

  • tar command creates tar files by converting a group of files into an archive. It also can extract tar archives, display a list of the files included in the archive, add additional files to an existing archive, and various other kinds of operations.
  • tar was designed for creating archives to store files on magnetic tape, which is why its name “Tape Archive”
  • There are two versions of tar, BSD tar and GNU tar, with some functional differences. Most linux systems come with GNU tar pre-installed by default.

tar syntax

  • tar [operation_and_options] [archive_name] [file_name(s)]
  • operation
    • –create (-c) == create a new tar archive
    • –extract (-x) == extract the entire archive or one or more files from an archive
    • –list (-t) == display a list of the files included in the archive
  • options
    • –verbose (-v) == show the files being processed by the tar command
    • –file=archive-name (-f archive-name) == specifies the archive name

creating tar archive

  • tar supports a vast range of compression programs such as gzip, bzip2, lzip, lzma, lzop, xz, compress.
  • It is an accepted convention to append the compressor suffix to the archive file name.
  • e.g. an archive has been compressed with gzip, it should be named archive.tar.gz
1
2
3
4
5
6
7
8
9
10
11
12
#create an archive named archive.tar with file1 - 3
tar -cf archive.tar file1 file2 file2 file3
tar --create --file=archive.tar file1 file2 file3

#create an archive named backup.tar of the /home/user directory
tar -cf backup.tar /home/usr

#create tar gz archive, the '-z' option tells tar to compress the archive using the gizp
tar -czf archive.tar.gz file1 file2

#create tar bzip archive file
tar -cjf archive.tar.bz2 file1 file2

listing tar archives

1
2
tar -tf archive.tar
tar -tvf archive.tar

extracting tar archive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
tar -xf archive.tar

#extract the archive contents to the /opt/files directory
tar -xf archive.tar -C /opt/files

#extracting files from compressed archive
tar -xvf archive.tar.gz
tar -xvf archive.tar.bz2

#extracting specific files from a tar archive
tar -xvf archive.tar file1 file2

#extracting specific directory from a tar archive
tar -xvf archive.tar dir1 dir2

#extracting files from a tar archive using wildcard
#switch and quote the pattern to prevent the shell from interpreting it
#to extract files whose names end in .js
tar -xvf archive.tar --wildcards '*.js'

adding files to existing tar archive

1
2
#use the --append(-r) operation
tar -rvf archive.tar newfile

removing files from a tar archive

1
2
3
#use the --delete operation to remove files from an archive
#remove the file1 from archive.tar
tar --delete -f archive.tar file1