tar (gnutar)

Create, add files to, or extract files from an archive file in gnutar format, called a tarfile. Tape ARchiver; manipulate "tar" archive files.

Syntax
      tar [bundled-flags args] [file | pattern ...]
      tar {-c} [options] [files | directories]
      tar {-r | -u} -f archive-file [options] [files | directories]
      tar {-t | -x} [options] [patterns]

tar creates and manipulates streaming archive files.
This implementation can extract from tar, pax, cpio, zip, jar, ar, and ISO 9660 cdrom images and can create tar, pax, cpio, ar, and shar archives.

The first synopsis form shows a 'bundled' option word. This usage is provided for compatibility with historical implementations. See COMPATIBILITY below for details.

     The other synopsis forms show the preferred usage.
     The first option to tar is a mode indicator from the following list:

     -c    Create a new archive containing the specified items.
     -r    Like -c, but new entries are appended to the archive.
           Note that this only works on uncompressed archives stored in regular files. The -f option is required.
     -t    List archive contents to stdout.
     -u    Like -r, but new entries are added only if they have a modification date newer
           than the corresponding entry in the archive.  Note that this
           only works on uncompressed archives stored in regular files.  The -f option is required.
     -x    Extract to disk from the archive.  If a file with the same name appears more than once in the
           archive, each copy will be extracted, with later copies overwriting (replacing) earlier copies.

In -c, -r, or -u mode, each specified file or directory is added to the archive in the order specified
on the command line. By default, the contents of each directory are also archived.

In extract or list mode, the entire command line is read and parsed before the archive is opened.
The pathnames or patterns on the command line indicate which items in the archive should be processed.
Patterns are shell-style globbing patterns as documented in tcsh(1).

Options
      Unless specifically stated otherwise, options are applicable in all operating modes.

     @archive
         (c and r mode only) The specified archive is opened and the entries in it will be appended
         to the current archive.  As a simple example,
              tar -c -f - newfile @original.tar
         writes a new archive to standard output containing a file newfile and all of the entries
         from original.tar.  In contrast,
              tar -c -f - newfile original.tar
         creates a new archive with only two entries.  Similarly,
              tar -czf - --format pax @-
         reads an archive from standard input (whose format will be determined automatically) and
         converts it into a gzip-compressed pax-format archive on stdout.
         In this way, tar can be used to convert archives from one format to another.

     -b blocksize
         Specify the block size, in 512-byte records, for tape drive I/O.
         As a rule, this argument is only needed when reading from or writing to tape drives, and
         usually not even then as the default block size of 20 records (10240 bytes) is very common.

     -C directory
         In c and r mode, this changes the directory before adding the following files.
         In x mode, change directories after opening the archive but before extracting entries from the archive.

     --check-links
         (c and r modes only) Issue a warning message unless all links to each file are archived.

     --chroot
         (x mode only) chroot() to the current directory after processing any -C options
         and before extracting any files.

     --exclude pattern
         Do not process files or directories that match the specified pattern.
         Note that exclusions take precedence over patterns or filenames
         specified on the command line.

     --format format
         (c, r, u mode only) Use the specified format for the created archive.
         Supported formats include 'cpio', 'pax'', 'shar', and 'ustar'.  Other formats may also be supported;
         see libarchive-formats(5) for more information about currently-supported formats.
         In r and u modes, when extending an existing archive, the format specified here must be compatible
         with the format of the existing archive on disk.

     -f file
         Read the archive from or write the archive to the specified file.
         The filename can be - for standard input or standard output.

     -H  (c and r mode only) Symbolic links named on the command line will be followed;
         the target of the link will be archived, not the link itself.

     -h  (c and r mode only) Synonym for -L.

     -I  Synonym for -T.

     --include pattern
         Process only files or directories that match the specified pattern.
         Note that exclusions specified with --exclude take precedence over inclusions.
         If no inclusions are explicitly specified, all entries are processed by default.
         The --include option is especially useful when filtering archives.  For example, the command
                   tar -c -f new.tar --include='*foo*' @old.tgz
         creates a new archive new.tar containing only the entries from old.tgz containing the string 'foo'.


     -j  (c mode only) Compress the resulting archive with bzip2(1).
         In extract or list modes, this option is ignored.  Note that, unlike other tar
         implementations, this implementation recognizes bzip2 compression automatically when reading archives.

     -k  (x mode only) Do not overwrite existing files.  In particular, if a file appears more than once
         in an archive, later copies will not overwrite earlier copies.

     --keep-newer-files
         (x mode only) Do not overwrite existing files that are newer than the versions
          appearing in the archive being extracted.

     -L  (c and r mode only) All symbolic links will be followed.
         Normally, symbolic links are archived as such.
         With this option, the target of the link will be archived instead.

     -l  This is a synonym for the --check-links option.

     -m  (x mode only) Do not extract modification time.
         By default, the modification time is set to the time stored in the archive.

     -n  (c, r, u modes only) Do not recursively archive the contents of directories.

     --newer date
         (c, r, u modes only) Only include files and directories newer than the specified date.
         This compares ctime entries.

     --newer-mtime date
         (c, r, u modes only) Like --newer, except it compares mtime entries instead of ctime entries.

     --newer-than file
         (c, r, u modes only) Only include files and directories newer than the specified file.
         This compares ctime entries.

     --newer-mtime-than file
         (c, r, u modes only) Like --newer-than, except it compares mtime entries instead of ctime entries.

     --nodump
         (c and r modes only) Honor the nodump file flag by skipping this file.

     --null  (use with -I, -T, or -X) Filenames or patterns are separated by null characters, not by newlines.
         This is often used to read filenames output by the -print0 option to find(1).

     --numeric-owner
         (x mode only) Ignore symbolic user and group names when restoring archives to disk, only
          numeric uid and gid values will be obeyed.

     -O  (x, t modes only) In extract (-x) mode, files will be written to standard out rather than
         being extracted to disk.  In list (-t) mode, the file listing will be written to stderr rather than the usual stdout.

     -o  (x mode) Use the user and group of the user running the program rather than those specified
         in the archive.  Note that this has no significance unless -p is specified, and the program
         is being run by the root user.  In this case, the file modes and flags from the archive will
         be restored, but ACLs or owner information in the archive will be discarded.

     -o  (c, r, u mode) A synonym for --format ustar

     --one-file-system
         (c, r, and u modes) Do not cross mount points.

     --options options
         Select optional behaviors for particular modules.
         The argument is a text string containing comma-separated keywords and values.
         These are passed to the modules that handle particular formats to control how those formats will behave.
         Each option has one of the following forms:
             key=value
                     The key will be set to the specified value in every module that supports it.
                     Modules that do not support this key will ignore it.
             key     The key will be enabled in every module that supports it.  This is equivalent to key=1.
             !key    The key will be disabled in every module that supports it.
             module:key=value, module:key, module:!key
                     As above, but the corresponding key and value will be provided only to modules whose name matches module.

             The currently supported modules and keys are:
             iso9660:joliet
                     Support Joliet extensions.  This is enabled by default, use !joliet or iso9660:!joliet to disable.
             iso9660:rockridge
                     Support Rock Ridge extensions.  This is enabled by default, use !rockridge or iso9660:!rockridge to disable.
             gzip:compression-level
                     A decimal integer from 0 to 9 specifying the gzip compression level.
             xz:compression-level
                     A decimal integer from 0 to 9 specifying the xz compression level.
             mtree:keyword
                     The mtree writer module allows you to specify which mtree keywords will be included in the output.  Supported keywords include:
                     cksum, device, flags, gid, gname, indent, link, md5, mode, nlink, rmd160, sha1, sha256, sha384, sha512, size, time, uid, uname.
                     The default is equivalent to: ``device, flags, gid, gname, link, mode, nlink, size, time, type, uid, uname''.
             mtree:all
                     Enables all of the above keywords.  You can also use mtree:!all to disable all keywords.
             mtree:use-set
                     Enable generation of /set lines in the output.
             mtree:indent
                     Produce human-readable output by indenting options and splitting lines to fit into 80 columns.
             zip:compression=type
                     Use type as compression method.  Supported values are store (uncompressed) and deflate (gzip algorithm).
             If a provided option is not supported by any module, that is a fatal error.

     -P  Preserve pathnames.
         By default, absolute pathnames (those that begin with a / character) have the leading slash
         removed both when creating archives and extracting from them.  Also, tar will refuse to extract
         archive entries whose pathnames contain .. or whose target directory would be altered by a symlink.
         This option suppresses these behaviors.

     -p  (x mode only) Preserve file permissions.
         Attempt to restore the full permissions, including owner, file modes, file flags and ACLs, if available,
         for each item extracted from the archive.  By default, newly-created files are owned by the user
         running tar, the file mode is restored for newly-created regular files, and all other types of entries
         receive default permissions.  If tar is being run by root, the default is to restore the owner unless
         the -o option is also specified.

     -q (--fast-read)
         (x and t mode only) Extract or list only the first archive entry that matches each pattern or filename operand.
         Exit as soon as each specified pattern or filename has been matched.
         By default, the archive is always read to the very end, since there can be multiple entries
         with the same name and, by convention, later entries overwrite earlier entries.
         This option is provided as a performance optimization.

     -S  (x mode only) Extract files as sparse files.
         For every block on disk, check first if it contains only NULL bytes and seek over it otherwise.
         This works similiar to the conv=sparse option of dd.

     --strip-components count
         (x mode only) Remove the specified number of leading path elements.
         Pathnames with fewer elements will be silently skipped.  Note that the pathname is edited after
         checking inclusion/exclusion patterns but before security checks.

     -s pattern
         Modify file or archive member names according to pattern.
         The pattern has the format /old/new/[gps] where old is a basic regular expression, new is the
         replacement string of the matched part, and the optional trailing letters modify how the
         replacement is handled.  If old is not matched, the pattern is skipped.
         Within new, ~ is substituted with the match, 1 to 9 with the content of the corresponding
         captured group.  The optional trailing g specifies that matching should continue after
          the matched part and stopped on the first unmatched pattern.
         The optional trailing s specifies that the pattern applies to the value of symbolic links.
         The optional trailing p specifies that after a successful substitution the original path
         name and the new path name should be printed to standard error.

     -T filename
         In x or t mode, tar will read the list of names to be extracted from filename.
         In c mode, tar will read names to be archived from filename.
         The special name '-C' on a line by itself will cause the current directory to be
         changed to the directory specified on the following line.
         Names are terminated by newlines unless --null is specified.
         Note that --null also disables the special handling of lines containing '-C'.

     -U  (x mode only) Unlink files before creating them.
         Without this option, tar overwrites existing files, which preserves existing hardlinks.
         With this option, existing hardlinks will be broken, as will any symlink that would affect
         the location of an extracted file.

     --use-compress-program program
         Pipe the input (in x or t mode) or the output (in c mode) through program instead of
         using the builtin compression support.

     -v  Produce verbose output.  In create and extract modes, tar will list each file name as
         it is read from or written to the archive.
         In list mode, tar will produce output similar to that of ls(1).
         Additional -v options will provide additional detail.

     --version
         Print version of tar and libarchive, and exit.

     -w  Ask for confirmation for every action.

     -X filename
         Read a list of exclusion patterns from the specified file.
         See --exclude for more information about the handling of exclusions.

     -y  (c mode only) Compress the resulting archive with bzip2(1).
         In extract or list modes, this option is ignored.  Note that, unlike other tar implementations, 
         this implementation recognizes bzip2 compression automatically when reading archives.

     -z  (c mode only) Compress the resulting archive with gzip(1).
         In extract or list modes, this option is ignored.  Note that, unlike other tar implementations,
         this implementation recognizes gzip compression automatically when reading archives.

     -Z  (c mode only) Compress the resulting archive with compress(1).
         In extract or list modes, this option is ignored.  Note that, unlike other tar implementations,
         this implementation recognizes compress compression automatically when reading archives.

Environment

The following environment variables affect the execution of tar:

LANG The locale to use. See environ(7) for more information.
TZ The timezone to use when displaying dates. See environ(7) for more information.

Exit Status

The tar utility exits 0 on success, and >0 if an error occurs.

Examples

To tar and zip a file

  tar -czvf MyArchive.tgz Source_file 
or in full
  tar --create --gzip --verbose --file=MyArchive.tgz Source_file

To view a detailed table of contents for this archive:

 tar -tvf MyArchive.tgz

To tar a folder (with all sub-folders and files)

  tar czf /volumes/myexternaldrive/backup01.tgz myfolder

The reverse process to extract the file

  tar -xzvf MyArchive.tgz Destination_file 
or
  tar --extract --gunzip --verbose --file=MyArchive.tgz Destination_file

  tar xzvf /volumes/myexternaldrive/backup01.tgz myfolder/subfolder/thefiletorestore

Extract a file, autodetecting the format, in this case an xz archive:

  tar -xf some.tar.xz

To extract all the C sources and headers from an archive named backup.tar:

  tar xf backup.tar '*.[ch]'

Note that the pattern must be quoted to prevent the shell from attempting to expand it according the files in the current working directory (the shell does not have access to the list of files in the archive, of course).

To move file hierarchies, use a command line like this:

  tar -cf - -C srcdir . | tar xpf - -C destdir

To create a compressed archive on diskette, using gzip(1), use a command-line like:

  tar --block-compress -z -c -v -f /dev/fd1a -b 36 tar/


Note that you cannot mix bundled flags and --style flags; you can use single-letter flags in the manner above, rather than having to type tar --block-compress --gzip --verbose --file /dev/fd1a --block-size 20 tar/

The above-created diskette can be listed with
tar tvfbz /dev/fd1a 36

To join two gnutar archives into a single archive, use

tar Af archive1.tar archive2.tar

which will add the files contained in archive2.tar onto the end of
archive1.tar (note that this can't be done by simply typing:

cat archive2.tar >> archive1.tar

because of the end-of-file block at the end of a gnutar archive).

To archive all files from the directory srcdir, which were modified after
Feb. 9th 1997, 13:00 h, use

   tar -c -f backup.tar --newer-mtime 'Feb 9 13:15 1997' srcdir/

Other possible time specifications are `02/09/97 13:15', `1997-02-09
13:15', `13:15 9 Feb 1997', `9 Feb 1997 13:15', `Feb. 9, 1997 1:15pm',
`09-Feb', `3 weeks ago' or `May first Sunday'.  To specify the correct
time zone use either e.g. `13:15 CEST' or `13:15+200'.

Notes

Always tar -t before tar -x to check if the archive contents have been placed inside one subdirectory or will just spill all over the current directory.

The -C feature does not work like historical gnutar programs, and is probably untrustworthy.

The -A command should work to join an arbitrary number of gnutar archives together, but it does not; attempting to do so leaves the end-of-archive blocks in place for the second and subsequent archives.

The gnutar file format is a semi fixed width field format, and the field for device numbers were designed for 16 bit (8 major, 8 minor) and can not absorb our 32 bit (8 major, 16+8 minor) numbers.

Environment Variables

     POSIXLY_CORRECT  Normally, gnutar will process flag arguments that appear
        in the file list.  If set in the environment, this
        causes gnutar to consider the first non-flag argument to
        terminate flag processing, as per the POSIX specification.

     SHELL       In interactive mode, a permissible response to the
        prompt is to request to spawn a subshell, which will be
        /bin/sh unless the SHELL variable is set.

     SIMPLE_BACKUP_SUFFIX
        Sets the backup suffix used by gnutar.  Default is '~'.

     TAPE       Changes gnutar's default tape drive /dev/sa0 (which is still
        overridden by the -f flag).

     TAR_OPTIONS      The environment variable TAR_OPTIONS can hold a set of
        default options for gnutar.  These options are inter-
        preted first and can be overwritten by explicit command
        line parameters.

     TAR_RSH       The TAR_RSH environment variable allows you to override
        the default shell used as the transport for gnutar.

     VERSION_CONTROL  Sets the backup method used by gnutar.  Possible values:

        t, numbered      Make numbered backups

        nil, existing    Numbered if numbered backups exist,
           simple otherwise

        never, simple    Always make simple backups
    
        Default behaviour is 'existing'.

"To disarm the bomb simply enter a valid tar command on your first try. No Googling" ~ XKCD

Related macOS commands:

bzip2(1)
cpio - Copy files to and from archives.
compress - compress and expand data.
gzip - Compress or decompress files.
pax(1)
rmt - remote magtape protocol module.
info tar


 
Copyright © SS64.com 1999-2019
Some rights reserved