Timur Gafforov
Timur Gafforov

Reputation: 761

tar file preserves full path. how to stop it?

I am trying to create a tar archive on my server through PHP as follows:

exec('tar -cvf myfile.tar tmp_folder/innerfolder/');

It works fine, but the saved file preserves the full path including tmp_folder/innerfolder/ I am creating those on the fly for users, so it's a bit unusable for users to have this path while extracting. I have reviewed this topic - How to strip path while archiving with TAR , but in the explanation the guy doesn't give an example, and I don't quite understand what to do.

Please, tell me with an example, how to add files to tar in a way that it does not preserve the 'tmp_folder/innerfolder/' part in archive?

Thanks in advance

Upvotes: 3

Views: 10804

Answers (5)

Ville
Ville

Reputation: 4346

If you want to preserve the current directory name but not the full path to it, try something like this (executed from within the directory that you want to tar; assumes bash/zsh):

ORIGDIR=${PWD##*/}
tar -C `dirname $PWD` -cvf ../archive.tar $ORIGDIR

Here's some detail; first:

ORIGDIR=${PWD##*/}

.. stores the current directory name (i.e. the name of the directory you're in). Then, in the tar command:

-C `dirname $PWD`

.. switches tar's "working directory" from the standard root ("/") to the parent of the folder you want to archive. Strangely the -C switch only affects the path for building the archive, but not the location the archive itself will be stored in. Hence you'll still have to prefix the archive name with "../", or else tar will place it within the folder you started the command in. Finally, $ORIGDIR is relative to the parent directory, and so it and its contents are archived recursively into the tar (but without the path leading to it).

Upvotes: 0

Senhorzim
Senhorzim

Reputation: 141

You can use --transform

tar -cf files.tar --transform='s,/your/path/,,' /your/path/file1 /your/path/file2
tar -tf files.tar
file1
file2

More info: http://www.gnu.org/software/tar/manual/html_section/transform.html

Upvotes: 2

amitchhajer
amitchhajer

Reputation: 12830

tar czf ~/backup.tgz --directory=/path filetotar

Upvotes: 0

user1549550
user1549550

Reputation:

Use the -C option to tar:

tar -C tmp_folder/innerfolder -cvf myfile.tar .

Upvotes: 13

Doon
Doon

Reputation: 20232

you can cheat..

exec('cd /path/to/tmp_folder/ && tar -cvf /path/to/myfile.tar innerfolder/');

This would would give your users just the innerfolder when they extracted the tarball

Upvotes: 3

Related Questions