Sysadmins Most Used Tar Command Examples in Linux

undefined

In this article we will discuss the using of tar command to archive Linux files, and directories. We will show you how to create archive, how to list files in an existing archive, how to extract files from archive, and how to compress your archive using different compression types. We will show you how to add new files to existing archive, extract certain files from archive, and add updated versions of files existing in an archive.

Tar is a very powerful tool for archiving files, and directories in Linux systems, it has many options than you can imagine, and for that it can be used in many situations in Linux. In another article, I’ll use tar to perform a full, and incremental backups for my Linux files, and directories, and will include the shell script that perform the backups.

Part 1: Definition, And Usages.

The tar program is used to creates and manipulates “archives” which are actually collections of many other files; the program provides users with an organized and systematic method for controlling a large amount of data. The name “tar” originally came from the phrase “Tape ARchive”, but archives need not (and these days, typically do not) reside on tapes.

We can use tar archives in many ways, but the most usage of tar command found in storage, Backup, and transportation.

So, let’s start
Here’s the first command we will run, we need to show all options available with tar command, run the following command:

$ tar --help
Usage: tar [OPTION...] [FILE]...
GNU `tar' saves many files together into a single tape or disk archive, and can
restore individual files from the archive.

Examples:
 tar -cf archive.tar foo bar # Create archive.tar from files foo and bar.
 tar -tvf archive.tar # List all files in archive.tar verbosely.
 tar -xf archive.tar # Extract all files from archive.tar.

Main operation mode:

-A, --catenate, --concatenate append tar files to an archive
 -c, --create create a new archive
 -d, --diff, --compare find differences between archive and file system
 --delete delete from the archive (not on mag tapes!)
 -r, --append append files to the end of an archive
 -t, --list list the contents of an archive
 --test-label test the archive volume label and exit
 -u, --update only append files newer than copy in archive
 -x, --extract, --get extract files from an archive

Operation modifiers:

--check-device check device numbers when creating incremental
 archives (default)
 -g, --listed-incremental=FILE handle new GNU-format incremental backup
 -G, --incremental handle old GNU-format incremental backup
 --ignore-failed-read do not exit with nonzero on unreadable files
 --level=NUMBER dump level for created listed-incremental archive
 -n, --seek archive is seekable
 --no-check-device do not check device numbers when creating
 incremental archives
 --no-seek archive is not seekable
 --occurrence[=NUMBER] process only the NUMBERth occurrence of each file
 in the archive; this option is valid only in
 conjunction with one of the subcommands --delete,
 --diff, --extract or --list and when a list of
 files is given either on the command line or via
 the -T option; NUMBER defaults to 1
 --sparse-version=MAJOR[.MINOR]
 set version of the sparse format to use (implies
 --sparse)
 -S, --sparse handle sparse files efficiently

Overwrite control:

-k, --keep-old-files don't replace existing files when extracting,
 treat them as errors
 --keep-newer-files don't replace existing files that are newer than
 their archive copies
 --no-overwrite-dir preserve metadata of existing directories
 --overwrite overwrite existing files when extracting
 --overwrite-dir overwrite metadata of existing directories when
 extracting (default)
 --recursive-unlink empty hierarchies prior to extracting directory
 --remove-files remove files after adding them to the archive
 --skip-old-files don't replace existing files when extracting,
 silently skip over them
 -U, --unlink-first remove each file prior to extracting over it
 -W, --verify attempt to verify the archive after writing it

Select output stream:

--ignore-command-error ignore exit codes of children
 --no-ignore-command-error treat non-zero exit codes of children as
 error
 -O, --to-stdout extract files to standard output
 --to-command=COMMAND pipe extracted files to another program

Handling of file attributes:

--atime-preserve[=METHOD] preserve access times on dumped files, either
 by restoring the times after reading
 (METHOD='replace'; default) or by not setting the
 times in the first place (METHOD='system')
 --delay-directory-restore delay setting modification times and
 permissions of extracted directories until the end
 of extraction
 --group=NAME force NAME as group for added files
 --mode=CHANGES force (symbolic) mode CHANGES for added files
 --mtime=DATE-OR-FILE set mtime for added files from DATE-OR-FILE
 -m, --touch don't extract file modified time
 --no-delay-directory-restore
 cancel the effect of --delay-directory-restore
 option
 --no-same-owner extract files as yourself (default for ordinary
 users)
 --no-same-permissions apply the user's umask when extracting permissions
 from the archive (default for ordinary users)
 --numeric-owner always use numbers for user/group names
 --owner=NAME force NAME as owner for added files
 -p, --preserve-permissions, --same-permissions
 extract information about file permissions
 (default for superuser)
 --preserve same as both -p and -s
 --same-owner try extracting files with the same ownership as
 exists in the archive (default for superuser)
 -s, --preserve-order, --same-order
 sort names to extract to match archive

Handling of extended file attributes:

--acls Enable the POSIX ACLs support
 --no-acls Disable the POSIX ACLs support
 --no-selinux Disable the SELinux context support
 --no-xattrs Disable extended attributes support
 --selinux Enable the SELinux context support
 --xattrs Enable extended attributes support
 --xattrs-exclude=MASK specify the exclude pattern for xattr keys
 --xattrs-include=MASK specify the include pattern for xattr keys

Device selection and switching:

-f, --file=ARCHIVE use archive file or device ARCHIVE
 --force-local archive file is local even if it has a colon
 -F, --info-script=NAME, --new-volume-script=NAME
 run script at end of each tape (implies -M)
 -L, --tape-length=NUMBER change tape after writing NUMBER x 1024 bytes
 -M, --multi-volume create/list/extract multi-volume archive
 --rmt-command=COMMAND use given rmt COMMAND instead of rmt
 --rsh-command=COMMAND use remote COMMAND instead of rsh
 --volno-file=FILE use/update the volume number in FILE

Device blocking:

-b, --blocking-factor=BLOCKS BLOCKS x 512 bytes per record
 -B, --read-full-records reblock as we read (for 4.2BSD pipes)
 -i, --ignore-zeros ignore zeroed blocks in archive (means EOF)
 --record-size=NUMBER NUMBER of bytes per record, multiple of 512

Archive format selection:

-H, --format=FORMAT create archive of the given format

FORMAT is one of the following:

gnu GNU tar 1.13.x format
 oldgnu GNU format as per tar <= 1.12
 pax POSIX 1003.1-2001 (pax) format
 posix same as pax
 ustar POSIX 1003.1-1988 (ustar) format
 v7 old V7 tar format

--old-archive, --portability
 same as --format=v7
 --pax-option=keyword[[:]=value][,keyword[[:]=value]]...
 control pax keywords
 --posix same as --format=posix
 -V, --label=TEXT create archive with volume name TEXT; at
 list/extract time, use TEXT as a globbing pattern
 for volume name

Compression options:

-a, --auto-compress use archive suffix to determine the compression
 program
 -I, --use-compress-program=PROG
 filter through PROG (must accept -d)
 -j, --bzip2 filter the archive through bzip2
 -J, --xz filter the archive through xz
 --lzip filter the archive through lzip
 --lzma filter the archive through lzma
 --lzop
 --no-auto-compress do not use archive suffix to determine the
 compression program
 -z, --gzip, --gunzip, --ungzip filter the archive through gzip
 -Z, --compress, --uncompress filter the archive through compress

Local file selection:

--add-file=FILE add given FILE to the archive (useful if its name
 starts with a dash)
 --backup[=CONTROL] backup before removal, choose version CONTROL
 -C, --directory=DIR change to directory DIR
 --exclude=PATTERN exclude files, given as a PATTERN
 --exclude-backups exclude backup and lock files
 --exclude-caches exclude contents of directories containing
 CACHEDIR.TAG, except for the tag file itself
 --exclude-caches-all exclude directories containing CACHEDIR.TAG
 --exclude-caches-under exclude everything under directories containing
 CACHEDIR.TAG
 --exclude-tag=FILE exclude contents of directories containing FILE,
 except for FILE itself
 --exclude-tag-all=FILE exclude directories containing FILE
 --exclude-tag-under=FILE exclude everything under directories
 containing FILE
 --exclude-vcs exclude version control system directories
 -h, --dereference follow symlinks; archive and dump the files they
 point to
 --hard-dereference follow hard links; archive and dump the files they
 refer to
 -K, --starting-file=MEMBER-NAME
 begin at member MEMBER-NAME in the archive
 --newer-mtime=DATE compare date and time when data changed only
 --no-null disable the effect of the previous --null option
 --no-recursion avoid descending automatically in directories
 --no-unquote do not unquote filenames read with -T
 --null -T reads null-terminated names, disable -C
 -N, --newer=DATE-OR-FILE, --after-date=DATE-OR-FILE
 only store files newer than DATE-OR-FILE
 --one-file-system stay in local file system when creating archive
 -P, --absolute-names don't strip leading `/'s from file names
 --recursion recurse into directories (default)
 --suffix=STRING backup before removal, override usual suffix ('~'
 unless overridden by environment variable
 SIMPLE_BACKUP_SUFFIX)
 -T, --files-from=FILE get names to extract or create from FILE
 --unquote unquote filenames read with -T (default)
 -X, --exclude-from=FILE exclude patterns listed in FILE

File name transformations:

--strip-components=NUMBER strip NUMBER leading components from file
 names on extraction
 --transform=EXPRESSION, --xform=EXPRESSION
 use sed replace EXPRESSION to transform file
 names

File name matching options (affect both exclude and include patterns):

--anchored patterns match file name start
 --ignore-case ignore case
 --no-anchored patterns match after any `/' (default for
 exclusion)
 --no-ignore-case case sensitive matching (default)
 --no-wildcards verbatim string matching
 --no-wildcards-match-slash wildcards do not match `/'
 --wildcards use wildcards (default)
 --wildcards-match-slash wildcards match `/' (default for exclusion)

Informative output:

--checkpoint[=NUMBER] display progress messages every NUMBERth record
 (default 10)
 --checkpoint-action=ACTION execute ACTION on each checkpoint
 --full-time print file time to its full resolution
 --index-file=FILE send verbose output to FILE
 -l, --check-links print a message if not all links are dumped
 --no-quote-chars=STRING disable quoting for characters from STRING
 --quote-chars=STRING additionally quote characters from STRING
 --quoting-style=STYLE set name quoting style; see below for valid STYLE
 values
 -R, --block-number show block number within archive with each message
 
 --show-defaults show tar defaults
 --show-omitted-dirs when listing or extracting, list each directory
 that does not match search criteria
 --show-transformed-names, --show-stored-names
 show file or archive names after transformation
 --totals[=SIGNAL] print total bytes after processing the archive;
 with an argument - print total bytes when this
 SIGNAL is delivered; Allowed signals are: SIGHUP,
 SIGQUIT, SIGINT, SIGUSR1 and SIGUSR2; the names
 without SIG prefix are also accepted
 --utc print file modification times in UTC
 -v, --verbose verbosely list files processed
 --warning=KEYWORD warning control
 -w, --interactive, --confirmation
 ask for confirmation for every action

Compatibility options:

-o when creating, same as --old-archive; when
 extracting, same as --no-same-owner

Other options:

-?, --help give this help list
 --restrict disable use of some potentially harmful options
 --usage give a short usage message
 --version print program version

Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.

The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.
The version control may be set with --backup or VERSION_CONTROL, values are:

none, off never make backups
 t, numbered make numbered backups
 nil, existing numbered if numbered backups exist, simple otherwise
 never, simple always make simple backups

Valid arguments for the --quoting-style option are:

literal
 shell
 shell-always
 c
 c-maybe
 escape
 locale
 clocale

*This* tar defaults to:
--format=gnu -f- -b20 --quoting-style=escape --rmt-command=/etc/rmt
--rsh-command=/usr/bin/ssh

Report bugs to <bug-tar@gnu.org>.

From the above output, we see the usage of the tar, it’s options, and main operation mode. It has a numerous options, and methods to use, which give us the ability to use it in a numerous situations. If you need more details on tar check the tar manual using “pinfo tar”, but the above output has enough info for any sysadmin. I’ll focus on the basic examples of using tar command to create,and manipulate archives.

Part 2: Basic Examples for Using Tar in Linux.

1. Creating a tar Archive File

I’ll create a tar archive file with name Public-26-07-2016.tar for a directory /home/mohammed.semari/Public/ in current working directory. See the following example.

$ tar -cvf Public-26-07-2016.tar /home/mohammed.semari/Public/
tar: Removing leading `/' from member names
/home/mohammed.semari/Public/
/home/mohammed.semari/Public/tar-directory/
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on CentOS 6 Linux system
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on CentOS 7 Linux system
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on Debian 8 Linux system
/home/mohammed.semari/Public/tar-directory/Sysadmins Most Used Linux iptables Rules Examples
/home/mohammed.semari/Public/tar-directory/.hidden_file_1
/home/mohammed.semari/Public/tar-directory/.hidden_file_2
/home/mohammed.semari/Public/tar-directory/.hidden_file_3
/home/mohammed.semari/Public/tar-directory/.hidden_file_4

Let’s discuss the each option we have used in the above command for creating tar archive file.

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

We see that our tar archive includes the hidden files existing in our directory.

2. Creating a compressed tar Archive File.

I’ll create a compressed archive file using two compression options z, and j; z option creates a gzip compressed files, and j creates a bz2 compressed files. Archives compressed with bz2 have a less size than the ones compressed with gzip, but it takes longer time. There is other compression options available with tar command, you can check them the usage of the tar in the beginning of this article. Archives compressed with gzip can have two extensions tar.gz and tgz “both are similar”, and Archives compressed with bz2 can have two extensions can have three extensions tar.bz2, tbz, and tb2 “All are similar”. I’ll create a compressed tar archive file for a directory /home/mohammed.semari/Public/ in current working directory with different compression options. See the following examples.

  • To create a gzip archive
$ tar -cvzf Public-26-07-2016.tar.gz /home/mohammed.semari/Public/
tar: Removing leading `/' from member names
/home/mohammed.semari/Public/
/home/mohammed.semari/Public/tar-directory/
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on CentOS 6 Linux system
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on CentOS 7 Linux system
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on Debian 8 Linux system
/home/mohammed.semari/Public/tar-directory/Sysadmins Most Used Linux iptables Rules Examples
/home/mohammed.semari/Public/tar-directory/.hidden_file_1
/home/mohammed.semari/Public/tar-directory/.hidden_file_2
/home/mohammed.semari/Public/tar-directory/.hidden_file_3
/home/mohammed.semari/Public/tar-directory/.hidden_file_4
  • To create a bz2 archive
$ tar -cvjf Public-26-07-2016.tar.bz2 /home/mohammed.semari/Public/
tar: Removing leading `/' from member names
/home/mohammed.semari/Public/
/home/mohammed.semari/Public/tar-directory/
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on CentOS 6 Linux system
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on CentOS 7 Linux system
/home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on Debian 8 Linux system
/home/mohammed.semari/Public/tar-directory/Sysadmins Most Used Linux iptables Rules Examples
/home/mohammed.semari/Public/tar-directory/.hidden_file_1
/home/mohammed.semari/Public/tar-directory/.hidden_file_2
/home/mohammed.semari/Public/tar-directory/.hidden_file_3
/home/mohammed.semari/Public/tar-directory/.hidden_file_4

Let’s discuss the compression options we have used in the above commands for creating a compressed tar archive file.

z, –gzip, –gunzip, –ungzip filter the archive through gzip
j, –bzip2 filter the archive through bzip2

Now, I’ll show you the size of each archive we created, run “ls -l” command as following.

$ ls -l
-rw-rw-r-- 1 mohammed.semari mohammed.semari 71680 Jul 27 05:59 Public-26-07-2016.tar
-rw-rw-r-- 1 mohammed.semari mohammed.semari 10656 Jul 27 06:04 Public-26-07-2016.tar.bz2
-rw-rw-r-- 1 mohammed.semari mohammed.semari 10934 Jul 27 06:02 Public-26-07-2016.tar.gz

We see that the uncompressed archive is the largest file, then the gzip compressed archive, then comes the bz2 compressed archive with the smallest size.

3. Untar Uncompressed, and Compressed Archived Files

To untar or extract a tar archive files, we will use option x (extract) instead of option c (create), this will untar the archived files in the current directory,but If you want untar in a different directory then use option -C (specified directory). For a compressed archive you must include the compression option used when creating the compressed archive, see the following examples.

  •  Untar uncompressed archive in current directory
$ tar -xvf Virtualization.tar 
Virtualization/
Virtualization/2003-xensosp.pdf
Virtualization/9781118231043_custom.pdf
Virtualization/Creating Development Environments with Vagrant, Second Edition.pdf
Virtualization/Docker Cookbook.pdf
Virtualization/Learning Docker.pdf
Virtualization/Mastering Citrix XenServer.pdf
Virtualization/Pro Vagrant.pdf
Virtualization/Virtualization in Education.pdf
Virtualization/Virtualization(1).pdf
Virtualization/Virtualization.pdf
Virtualization/virtualization1.pdf
Virtualization/Pro Docker.pdf
  •  Untar uncompressed archive in specified Directory
$ tar -xvf Public-26-07-2016.tar -C /
home/mohammed.semari/Public/
home/mohammed.semari/Public/tar-directory/
home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on CentOS 6 Linux system
home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on CentOS 7 Linux system
home/mohammed.semari/Public/tar-directory/Setup and Configure Basic iptables on Debian 8 Linux system
home/mohammed.semari/Public/tar-directory/Sysadmins Most Used Linux iptables Rules Examples
home/mohammed.semari/Public/tar-directory/.hidden_file_1
home/mohammed.semari/Public/tar-directory/.hidden_file_2
home/mohammed.semari/Public/tar-directory/.hidden_file_3
home/mohammed.semari/Public/tar-directory/.hidden_file_4

With using option -C, I can set the destination directory to extract my archive into. In my example I extracted the files into their original location “replaced the existing files”.

Untar compressed archive files

To untar any compressed archive created with any compression options, just use option x (extract) only, or use it with the compression option used when creating the compressed archive. Option x is enough, because it has the ability to determine the compression type used with the compressed archive. See the following examples.

  • Utar tar.gz Archive File
$ tar -xvf Storage.tar.gz 
Storage/
Storage/IP Storage Networking: IBM NAS and iSCSI Solutions.pdf
Storage/Introduction to Storage Area Networks and System Networking.pdf
Storage/Introduction to Storage Area Networks.pdf
  • Utar tar.bz2 Archive File
$ tar -xvf Storage.tar.bz2 
Storage/
Storage/IP Storage Networking: IBM NAS and iSCSI Solutions.pdf
Storage/Introduction to Storage Area Networks and System Networking.pdf
Storage/Introduction to Storage Area Networks.pdf

Of course, we can use option -C to set the destination directory to extract our archives into.

4. Listing the Content of Uncompressed, and Compressed tar Archive Files

To list the content of uncompressed, and compressed tar archive file, use tar command with option t (list content) for compressed, and uncompressed archived files. run the following commands:

  • Listing content of uncompressed tar archive file
$ tar -tvf www.mimastech.com.tar
-rw-r--r-- root/root 0 2016-07-05 11:10 www.mimastech.com_access_log
-rw-r--r-- root/root 1312862 2016-06-10 18:57 www.mimastech.com_access_log-20160613
-rw-r--r-- root/root 94619 2016-06-15 07:09 www.mimastech.com_access_log-20160619
-rw-r--r-- root/root 104992 2016-06-25 18:25 www.mimastech.com_access_log-20160626
-rw-r--r-- root/root 174593 2016-06-26 18:13 www.mimastech.com_access_log-20160705
-rw-r--r-- root/root 0 2016-06-05 10:44 www.mimastech.com_error_log
-rw-r--r-- root/root 70189 2016-04-16 05:49 www.mimastech.com_error_log-20160417
-rw-r--r-- root/root 837505 2016-04-19 05:58 www.mimastech.com_error_log-20160425
-rw-r--r-- root/root 1162 2016-06-01 00:13 www.mimastech.com_error_log-20160601
-rw-r--r-- root/root 29466 2016-06-02 06:53 www.mimastech.com_error_log-20160605
  • Listing content of gzip compressed tar archive file
$ tar -tvf www.mimastech.com.tar.gz 
-rw-r--r-- root/root 0 2016-07-05 11:10 www.mimastech.com_access_log
-rw-r--r-- root/root 1312862 2016-06-10 18:57 www.mimastech.com_access_log-20160613
-rw-r--r-- root/root 94619 2016-06-15 07:09 www.mimastech.com_access_log-20160619
-rw-r--r-- root/root 104992 2016-06-25 18:25 www.mimastech.com_access_log-20160626
-rw-r--r-- root/root 174593 2016-06-26 18:13 www.mimastech.com_access_log-20160705
-rw-r--r-- root/root 0 2016-06-05 10:44 www.mimastech.com_error_log
-rw-r--r-- root/root 70189 2016-04-16 05:49 www.mimastech.com_error_log-20160417
-rw-r--r-- root/root 837505 2016-04-19 05:58 www.mimastech.com_error_log-20160425
-rw-r--r-- root/root 1162 2016-06-01 00:13 www.mimastech.com_error_log-20160601
-rw-r--r-- root/root 29466 2016-06-02 06:53 www.mimastech.com_error_log-20160605
  • Listing content of bzip2 compressed tar archive file
$ tar -tvf www.mimastech.com.tar.bz2 
-rw-r--r-- root/root 0 2016-07-05 11:10 www.mimastech.com_access_log
-rw-r--r-- root/root 1312862 2016-06-10 18:57 www.mimastech.com_access_log-20160613
-rw-r--r-- root/root 94619 2016-06-15 07:09 www.mimastech.com_access_log-20160619
-rw-r--r-- root/root 104992 2016-06-25 18:25 www.mimastech.com_access_log-20160626
-rw-r--r-- root/root 174593 2016-06-26 18:13 www.mimastech.com_access_log-20160705
-rw-r--r-- root/root 0 2016-06-05 10:44 www.mimastech.com_error_log
-rw-r--r-- root/root 70189 2016-04-16 05:49 www.mimastech.com_error_log-20160417
-rw-r--r-- root/root 837505 2016-04-19 05:58 www.mimastech.com_error_log-20160425
-rw-r--r-- root/root 1162 2016-06-01 00:13 www.mimastech.com_error_log-20160601
-rw-r--r-- root/root 29466 2016-06-02 06:53 www.mimastech.com_error_log-20160605

In all of the above examples, we only use tar command with these options “tvf”

5. Extracting a Single / Multiple files from Uncompressed, and Compressed tar Archive File

To extract a single or multiple files from uncompressed, and compressed tar archive, first you need the names of the files, use the above listing examples to get the names of files you want to extract.

To extract these two files www.mimastech.com_access_log, and www.mimastech.com_error_log from the above example, run the following command:

$ tar -xvf www.mimastech.com.tar www.mimastech.com_access_log www.mimastech.com_error_log
www.mimastech.com_access_log
www.mimastech.com_error_log

And for gzip, bzip2 compressed archives, we get the same output

$ tar -xvf www.mimastech.com.tar.gz www.mimastech.com_access_log www.mimastech.com_error_log
www.mimastech.com_access_log
www.mimastech.com_error_log
$ tar -xvf www.mimastech.com.tar.bz2 www.mimastech.com_access_log www.mimastech.com_error_log
www.mimastech.com_access_log
www.mimastech.com_error_log

We must use a space separated names for the files we want to extract.

6. Adding Files or Directories to Uncompressed tar Archive File

To add files or directories to existing Uncompressed tar archived file we use the option r (append). Here,s I’ll append a file called “www.mimastech.com_access_log”, and a directory called “Storage” to uncompressed tar archive, see the following examples.

First, I’ll list the content of the archive I use:

$ tar -tvf logs.tar
-rw------- root/root 10641 2016-07-26 22:53 maillog
-rw------- root/root 48476 2016-07-05 10:19 maillog-20160705
-rw------- root/root 11968 2016-07-10 10:00 maillog-20160710
-rw------- root/root 32847 2016-07-17 10:25 maillog-20160717
-rw------- root/root 35622 2016-07-24 16:01 maillog-20160725
-rw------- root/root 1895536 2016-07-27 08:07 messages
-rw------- root/root 8215353 2016-07-05 11:10 messages-20160705
-rw------- root/root 2864733 2016-07-10 10:45 messages-20160710
-rw------- root/root 3852214 2016-07-17 11:10 messages-20160717
-rw------- root/root 9863240 2016-07-25 08:42 messages-20160725

Now, we add the file, and directory to this archive, using the following commands:

$ tar -rvf logs.tar www.mimastech.com_access_log Storage
www.mimastech.com_access_log
Storage/
Storage/IP Storage Networking: IBM NAS and iSCSI Solutions.pdf
Storage/Introduction to Storage Area Networks and System Networking.pdf
Storage/Introduction to Storage Area Networks.pdf

Now, list again the content of your archive, you will find the new file, and directory appended to the archive.

$ tar -tvf logs.tar 
-rw------- root/root 10641 2016-07-26 22:53 maillog
-rw------- root/root 48476 2016-07-05 10:19 maillog-20160705
-rw------- root/root 11968 2016-07-10 10:00 maillog-20160710
-rw------- root/root 32847 2016-07-17 10:25 maillog-20160717
-rw------- root/root 35622 2016-07-24 16:01 maillog-20160725
-rw------- root/root 1895536 2016-07-27 08:07 messages
-rw------- root/root 8215353 2016-07-05 11:10 messages-20160705
-rw------- root/root 2864733 2016-07-10 10:45 messages-20160710
-rw------- root/root 3852214 2016-07-17 11:10 messages-20160717
-rw------- root/root 9863240 2016-07-25 08:42 messages-20160725
-rw-r--r-- mohammed.semari/mohammed.semari 0 2016-07-05 11:10 www.mimastech.com_access_log
drwx------ mohammed.semari/mohammed.semari 0 2015-10-09 10:38 Storage/
-rw------- mohammed.semari/mohammed.semari 5179075 2013-12-05 15:39 Storage/IP Storage Networking: IBM NAS and iSCSI Solutions.pdf
-rw------- mohammed.semari/mohammed.semari 16300965 2013-12-05 15:37 Storage/Introduction to Storage Area Networks and System Networking.pdf
-rw------- mohammed.semari/mohammed.semari 4868780 2010-06-21 01:52 Storage/Introduction to Storage Area Networks.pdf
Hint:
1. tar command does not support appending files or directories to a compressed tar archives.

7. Updating Files or Directories existing in Uncompressed tar Archive File

To update files or directories existing in uncompressed tar archived file we use the option u (update), this option works only if the file is newer than it’s version in the tar archive. I’ll update logs.tar with the same file, and directory we appended to it in the above example, run the following command:

$ tar -uvf logs.tar www.mimastech.com_access_log Storage

You notice that nothing happened, because the tar archive has the same file, and directory, but If you did any modification to the file, and re-run the same command:

$ tar -uvf logs.tar www.mimastech.com_access_log Storage
www.mimastech.com_access_log

You see that the tar updated it’s existing file with the newer one, nothing happened to the directory.

Hint:
1. tar command does not support updating files or directories to a compressed tar archives.

8. Using Wildcard with tar archive command

By default tar is using the wildcard when it creates, extracts, updates, appends, etc… tar archives, we do not need to explicity add any option to enable the using of wildcard, just we directly use the wildcard, see the following examples:

  • Create uncompressed tar archive using wildcard for certain files
$ tar -cvf wildcard.tar www.*
www.anaproxy.com_error_log
www.anaproxy.com.tar
www.anaproxy.com.tar.bz2
www.anaproxy.com.tar.gz
www.mimastech.com_access_log
www.mimastech.com_error_log
www.mimastech.com_error_log-20160425
www.mimastech.com_error_log-20160601
www.mimastech.com.tar
www.mimastech.com.tar.bz2
www.mimastech.com.tar.gz
  • Create a compressed tar archive using wildcard for certain files
$ tar -cvzf wildcard.tar.gz www.*
www.anaproxy.com_error_log
www.anaproxy.com.tar
www.anaproxy.com.tar.bz2
www.anaproxy.com.tar.gz
www.mimastech.com_access_log
www.mimastech.com_error_log
www.mimastech.com_error_log-20160425
www.mimastech.com_error_log-20160601
www.mimastech.com.tar
www.mimastech.com.tar.bz2
www.mimastech.com.tar.gz
  • Extract certain files from uncompressed tar archive file using wildcard
$ tar -xvf logs.tar maillog*
maillog
maillog-20160705
maillog-20160710
maillog-20160717
maillog-20160725
  • Extract certain files from compressed tar archive file using wildcard
$ tar -xvf logs.tar.gz maillog*
maillog
maillog-20160705
maillog-20160710
maillog-20160717
maillog-20160725

9. Using exclude option with tar archive command

Tar command can create archives and exclude some files, and directories from being archived. This is important option for sysadmins who run deployments, i.e if you need to deploy a code from SCM “svn, github, etc…” you do not want to deploy the hidden scm files, here’s comes the importance of exclude option.

Next, I create a tar archive for a directory, and exclude the hidden .svn files, see the following command:

$ tar --exclude=.svn* -cvf www.mimastech.com.tar mimastech.com

The above command will create an archive with name www.mimastech.com.tar , and not include the scm files in “.svn” directories. We can use “–exclude-vcs” to exclude version control system directories, it’ll give the same result as the above one, run the following command:

$ tar --exclude-vcs -cvf www.mimastech.com1.tar mimastech.com

If we run “ls -l” command, we will see that both archived files are equal in size, as below:

$ ls -l
-rw-rw-r-- 1 mohammed.semari mohammed.semari 59351040 Jul 28 15:04 www.mimastech.com1.tar
-rw-rw-r-- 1 mohammed.semari mohammed.semari 59351040 Jul 28 15:03 www.mimastech.com.tar

Personally, I use “–exclude-vcs” in my work when creating archives for svn or github SCM. Sure, we can use this option when creating a compressed archives just we will add the compression options.
Finally, take care of the options order, i.e “–exclude and –exclude-vcs” comes first before the “-cvf” option

Summary

In this article we have explained the using of tar command with it’s options. We showed you how to create tar archive, how to list files in a tar archive, how to extract files from a tar archive, and how to update, and append files to a tar archive. We also included all options used with the tar command. We included examples for both uncompressed, and compressed tar archives.

I hope this article is good enough for you.
See you in other articles

If You Appreciate What We Do Here On Mimastech, You Should Consider:

  1. Stay Connected to: Facebook | Twitter | Google+
  2. Support us via PayPal Donation
  3. Subscribe to our email newsletters.
  4. Tell other sysadmins / friends about Us - Share and Like our posts and services

We are thankful for your never ending support.

One Comment to Sysadmins Most Used Tar Command Examples in Linux

  1. […] should have some experience in using tar command simply by reading our Sysadmins Most Used Tar Command Examples in Linux […]

Leave a Reply

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