Sunday, October 4, 2009

Linux - Tar Command Archiving Files

Linux - Tar Command Archiving Files

An archive is a collection of one or more files grouped together into a single file. The program tar (tape archive) is used in *nix to form an archive. This archive file is commonly called a tar file. Note that the tar file is not compressed. A compressed or uncompressed tar file is also commonly called a tarball. This is similar to the .iso files you see with the Windows operating system. We will see in the next section how to compress a tar file.

Create a Tar

Use the cvf option to create a tar (c stands for create),

$ cd
$ ls
a.out file1.c file3 src
$ tar cvf archive.tar file1.c file3
file1.c
file3
$ ls
a.out archive.tar file1.c file3 src

Note that the "tarred" files are not removed. This tar command would create an archive file named archive.tar which contains the files file1.c and file3. The v option to tar specifies that the program be verbose and display the files it is archiving as they are being archived. The c option means create an archive file. The f option means that what follows the options (the word "archive.tar") is to be the name of the archive file. It is common to give this file a .tar extension. Following the name of the archive file is a list of one or more filenames (or directories) to be archived.

To tar all of the .c files in a directory,

$ ls src
file01.c file02.c file03.c file01.o file02.o file03.o
$ cd src
$ tar cvf archive-c.tar *.c
file01.c
file02.c
file03.c
$ ls
archive-c.tar file01.c file02.c file03.c file01.o file02.o file03.o

Display Tar Contents

To list the contents of a tar archive to the screen, i.e., to see what is in the archive, use the t option (t stands for table of contents),

$ tar tf archive-c.tar
file01.c
file02.c
file03.c

Extract Files

To extract the files from a tar archive use the x (extract) option,

$ cd
$ mkdir gromulate
$ mv src/archive-c.tar gromulate
$ cd gromulate
$ tar xvf archive-c.tar
file01.c
file02.c
file03.c
$ ls
file01.c file02.c file03.c

The file names will be displayed as each of them is extracted (because of the v option).

To extract the tar directly to a different directory than the current directory, use the -C option.

$ tar xvf archive-c.tar -C fred/backup

 

Tar is often use to archive an entire directory and its subdirectories. In the example below, 'src' is a directory,

$ cd
$ ls src
file01.c file02.c file03.c file01.o file02.o file03.o
$ tar cvf src.tar src
file01.c
file02.c
file03.c
file01.o
file02.o
file03.o
$ ls
a.out file1.c file3 src src.tar
$ tar tf src.tar
file01.c
file02.c
file03.c
file01.o
file02.o
file03.o

Summary

Create a tar,

$ tar cvf name.tar fileSrc

 

View contents of a tar,

$ tar tf src.tar

 

Extract contents of a tar,

$ tar xvf archive-c.tar

 

Extract contents of a tar to a different directory,

$ tar xvf archive-c.tar -C filepath

 

No comments:

Post a Comment