Syntax: tar [[-]function] [options] filenames...
tar [[-]function] [options] -C directory-name...
Description: The tar command is most often used to archive files. In most cases, we will first collect all the data to back up in a single archive file, which we will compress later on. The process of archiving involves concatenating all listed files and taking out unnecessary blanks. In Linux, this is commonly done with the tar command. tar was originally designed to archive data on tapes, but it can also make archives, known as tarballs.
tar has many options, the most important ones are cited below:
-t: test, shows content of a tarball
-x: extract archive
-c: create archive
-f archivedevice: use archivedevice as source/destination for the tarball, the device defaults to the first tape device (usually /dev/st0 or something similar)
-j: filter through bzip2
Example: # tar cvf backup.tar /etc
packs all of the files in /etc into the tar archive backup.tar. The first argument to tar, "cvf", is the tar ``command.'' c tells tar to create a new archive file. v forces tar to use verbose mode, printing each file name as it is archived. The ``f'' option tells tar that the next argument, backup.tar, is the name of the archive to create. The rest of the arguments to tar are the file and directory names to add to the archive.
# tar xvf backup.tar /etc
will extract the tar file backup.tar in the current directory.
Old files with the same name are overwritten when extracting files into an existing directory.
Before extracting tar files it is important to know where the files should be unpacked. Let's say that you archive the following files: /etc/hosts, /etc/group, and /etc/passwd. If you use the command
# tar cvf backup.tar /etc/hosts/etc/group/etc/passwd
the directory name /etc/ is added to the beginning of each file name. In order to extract the files to the correct location, use
# cd /
# tar xvf backup.tar
because files are extracted with the path name saved in the archive file.
However, if you archive the files with the command
# cd /etc
# tar cvf hosts group passwd
the directory name is not saved in the archive file. Therefore, you need to ``cd /etc'' before extracting the files. As you can see, how the tar file is created makes a large difference in where you extract it. The command # tar tvf backup.tar can be used to display a listing of the archive's files without extracting them. You can see what directory the files in the archive are stored relative to, and extract the archive in the correct location.
Related: gzip, rman, sum, unshar