如何为 tar 指定不同的“顶级”名称?

how*_*ard 11 shell tar

我想 tar root (/) 并让它在 tar 存档中显示为 /abc。

是否有用于指定自定义顶级名称的 tar 标志?

ter*_*don 8

我能找到的最接近的是--transform选项。我不确定,但我猜这是一个仅限 GNU 的标志:

 --transform, --xform EXPRESSION
       use sed replace EXPRESSION to transform file names
Run Code Online (Sandbox Code Playgroud)

使用它,您可以传递sed替换命令并将其更改//abc

tar cf root.tgz --transform 's/^\//\/abc/' /
Run Code Online (Sandbox Code Playgroud)

这将/在创建存档时仍然打印路径,但/abc在您提取它时它们会变成。


另一种方法,如果您tar没有--transform选择是制作/abc一个符号链接/,然后指向它:

$ ln -s / /abc
$ tar chf root.tgz /abc
Run Code Online (Sandbox Code Playgroud)

-h是必不可少的,因为这告诉您tar要遵循链接:

 -h, --dereference
       follow symlinks; archive and dump the files they point to
Run Code Online (Sandbox Code Playgroud)

这将具有设置/abc为顶级目录的效果。