Bootstrap FreeKB - TAR - extract an archive
TAR - extract an archive

Updated:   |  TAR articles

Let's say you have a tar archive that contains files and directories.

~]# tar -tf example.tar
tmp/sample/
tmp/sample/bar.txt
tmp/sample/foo.txt

 

The tar command with the -x or --extract and -f or --file options will extract the contents of the tar archive. In this example, the contents of example.tar will be extracted into the present working directory. You will almost always want to also use the -p or --preserve-permissions flag, so that the file permissions are preserved.

AVOID TROUBLE

Let's say your tar archive contains tmp/sample/foo.txt and /tmp/sample/foo.txt already exists. In this scenario, /tmp/sample/foo.txt would be overwritten by tmp/sample/foo.txt in the tar archive.

tar --extract --preserve-permissions --file example.tar

 

Or, more commonly, the -xpf flag is used.

tar -xpf example.tar

 

The -v or --verbose option can be used to display the files being extracted.

~]# tar -xpvf example.tar
tmp/sample/
tmp/sample/bar.txt
tmp/sample/foo.txt

 

As an example, if your present working directory is /home/john.doe, following will be where the archive is extracted.

/home/john.doe/tmp/sample/
/home/john.doe/tmp/sample/bar.txt
/home/john.doe/tmp/sample/foo.txt

 

The -C or --directory options can be used to extract the contents to a specific directory. In this example, both of these commands have the same result, where the contents of example.tar are extracted to the / directory.

tar -xpf example.tar --directory /
cd /; tar -cf example.tar

 

The -z option will be needed if the archive is gzip compressed.

tar -zxpf example.tar.gz

 

The -j option will be needed if the archive is bz2 compressed.

tar -jxpf example.tar.bz2

 

To extract a single file from the archive, include the file exactly as it is listed in the archive.

tar -xpf example.tar path/to/example.txt

 

The -C or --directory option can be used to extract the single file to a certain directory.

tar -xpf example.tar --directory /tmp path/to/example.txt

 

The -k or --keep-old-files option can be used so that if the tar archive contains files that already exist in the target, the files will not be replaced by the file in the tar archive, and treated as an error.

tar -xkf example.tar --directory /tmp path/to/example.txt

 

Likewise, the --skip-old-files flag is very similar except that they will not be treated as errors and will be silently skipped.

tar --extract --skip-old-files -f example.tar --directory /tmp path/to/example.txt

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 369e3c in the box below so that we can be sure you are a human.