User Tools

Site Tools


relative_file_names_in_a_tar_archive

This is an old revision of the document!


Relative file names in a tar archive

Problem

If we tar the following directory

% tree --charset=unicode /tmp/expt
/tmp/expt
`-- insurance
    |-- auto.txt
    |-- condo.txt
    `-- rv.txt

1 directory, 3 files

using

% tar czvf insurance.tgz /tmp/expt/insurance 
tar: Removing leading `/' from member names
/tmp/expt/insurance/
/tmp/expt/insurance/auto.txt
/tmp/expt/insurance/rv.txt
/tmp/expt/insurance/condo.txt

then the file names in the .tgz contain the whole path releative to '/'.

% tar tzvf insurance.tgz                   
drwxr-xr-x rajulocal/rajulocal 0 2020-12-04 10:25 tmp/expt/insurance/
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 tmp/expt/insurance/auto.txt
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 tmp/expt/insurance/rv.txt
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 tmp/expt/insurance/condo.txt

But I want the paths to be relative to the 'insurance' directory. Something like

drwxr-xr-x rajulocal/rajulocal 0 2020-12-04 10:25 insurance/
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 insurance/auto.txt
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 insurance/rv.txt
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 insurance/condo.txt

Solution

Use the -C option while creating the tar archive.

% tar czvf insurance2.tgz -C /tmp/expt insurance
insurance/
insurance/auto.txt
insurance/rv.txt
insurance/condo.txt

Test the new archive.

% tar tzvf insurance2.tgz                       
drwxr-xr-x rajulocal/rajulocal 0 2020-12-04 10:25 insurance/
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 insurance/auto.txt
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 insurance/rv.txt
-rw-r--r-- rajulocal/rajulocal 0 2020-12-04 10:25 insurance/condo.txt

How it works

From the man page

% man tar
...
       -C, --directory=DIR
              Change  to DIR before performing any operations.  This option is order-sensitive, i.e. it affects all
              options that follow.

System information

Debian Buster

% tar --version
tar (GNU tar) 1.30
relative_file_names_in_a_tar_archive.1607098727.txt.gz · Last modified: 2020/12/04 16:18 by raju