tar

Basics

  • Archives files and directories

  • … togehter with all other UNIX entry types (⟶ UNIX specific)

  • Does not compress by itself ⟶ pipe

Modes

  • Pack (-c … “create”)

    $ tar -c -f file.tar directory}
    
  • Unpack (-x … “extract”)

    $ tar -x -f file.tar
    
  • View (-t … “tell”)

    $ tar -t -f file.tar
    

Creating And Viewing Archives

Takes a list of input directories, and adds them to the archive.

$ cd /usr/src/linux
$ tar -c -f /tmp/filesystems.tar Documentation/filesystems
$ tar -t -f /tmp/filesystems.tar
Documentation/filesystems/
Documentation/filesystems/ceph.txt
Documentation/filesystems/gfs2.txt
Documentation/filesystems/quota.txt
...

(De)Compression

As a convenience measure, tar is also capable of compressing what it creates. The following calls are equivalent:

$ tar -c -f file.tar.gz -z directory
$ tar -zcf file.tar.gz directory
$ tar -c -f - directory | gzip > file.tar.gz

Decompression likewise:

$ tar zxf file.tar.gz
$ tar ztf file.tar.gz
$ gzip -cd file.tar.gz | tar tf -

Etiquette

  • Caution: tar unpacks into the current working directory (unless you give -C to change CWD)

    • ⟶ use tar -t -f ... prior to unpacking

    • If there are many toplevel entries, you’ll be pouring a can of dirt into your livingroom

      $ tar ztf file.tar.gz
      
    • ⟶ grumble, create subdirectory, and unpack there

  • Be nice to others: always take care to archive only one toplevel directory

  • Refuses to add absolute paths to the archive

    $ tar cf /tmp/jfasch.tar /home/jfasch
    tar: Removing leading `/' from member names
    ...
    

Option Summary

Option

Description

-c

(c)reate archive

-x

e(x)tract archive

-t

(t)ell archive content

-f file

From/to file (special filename “-” for stdin/stdout)

-v

Verbose

-vv

More verbose

-z

Use gzip for (de)compression

-j

Use bzip2 for (de)compression

-C

(C)hange directory before you begin

-T file

Read list of entries from file (“-” to read from stdin)

Being Creative With The Pipe

  • Using tar to copy one directory to another

    $ tar -cf - -C one-directory . | \
           tar -xf - -C another-directory
    
  • Using ssh remote command execution (see here) to transfer an archive on the fly

    $ tar -jcf - -C ein-directory . | \
           ssh server 'tar -jxf - -C anderes-directory'
    
  • Dynamically creating a file list which tar reads from stdin

    $ ( cd /usr/src/linux; \
           find -name \*.h -o -name \*.c | \
           tar -cf - -T - ) | \
         tar -xf - -C anderes-directory