2

我正在尝试通过 PHP 在我的服务器上创建一个 tar 存档,如下所示:

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

它工作正常,但保存的文件保留了完整路径,包括 tmp_folder/innerfolder/ 我正在为用户动态创建这些路径,因此用户在提取时拥有此路径有点不可用。我已经回顾了这个主题 -如何在使用 TAR 归档时剥离路径,但是在解释中,这个人没有给出一个例子,我不太明白该怎么做。

请用一个例子告诉我,如何以不保留存档中的“tmp_folder/innerfolder/”部分的方式将文件添加到 tar?

提前致谢

4

5 回答 5

13

使用 -C 选项来 tar:

tar -C tmp_folder/innerfolder -cvf myfile.tar .
于 2012-09-21T14:39:59.710 回答
3

你可以作弊。。

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

这将使您的用户在提取 tarball 时只提供内部文件夹

于 2012-09-21T14:39:25.450 回答
2

您可以使用 --transform

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

更多信息:http ://www.gnu.org/software/tar/manual/html_section/transform.html

于 2013-07-12T19:08:25.327 回答
0
tar czf ~/backup.tgz --directory=/path filetotar
于 2012-09-21T14:45:48.337 回答
0

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).

于 2013-11-01T16:59:34.803 回答