Unix / Linux: Extract Tar File with Absolute Path

Objective: Extract a tar file with absolute path to a relative or different path. For example, if a tar arahive contains the file /etc/hosts, it has to be extracted to /home/user/etc/hosts instead.

Let’s say that you have the following tar archive that stores a file – /etc/hosts. This file has an absolute path as it has a leading slash ‘/‘.

$ tar tvf foo.tar
-rw-r--r-- root/root      1615 2016-05-18 21:59 /etc/hosts

We do not want our original /etc/hosts file to be overwritten when we extract this tar archive. To extract the file to a relative path, we can use the -C option to specify the target or relative directory. This is supported on GNU tar.

$ mkdir out

$ tar xvf rtar-linux.tar -C out
/etc/passwd

$ find out
out
out/etc
out/etc/hosts

As you can see from above, we created a directory called out and instructed tar to extract the contents to the out directory. Once the tar archive has been extracted, we can see that the /etc/hosts file is in the out directory.

If your tar program does not support the -C option, you can consider using pax. The -s option of pax can be used to modify filenames using regular expressions, based on sed. The format is: -s /old/new/ [gp]

The optional trailing g is as defined in the sed command. The optional trailing p causes successful substitutions to be written to standard error.

To extract to a relative path using pax, use the following syntax.

$  pax -r -s '!^/!out/!p' < foo.tar
/etc/hosts >> out/etc/hosts

$ find out
out
out/etc
out/etc/hosts

The regular expression that we passed to pax is to match a “/” at the beginning and replace it with “out/”.

This can also be achieved by using chroot but it’s a bit more troublesome.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }