13

I would like to tar root (/) and let it appear as /abc in the tar archive.

Is there a tar flag for specifying a custom top-level name?

1
  • Should the targets of symlinks also be be modified? For instance, if there's a /bin -> /usr/bin symlink, should it change to a /abc/bin -> /abc/usr/bin symlink? Aug 18, 2022 at 19:13

4 Answers 4

10

The closest I can find is the --transform option. I don't know for sure, but I'm guessing this is a GNU only flag:

 --transform, --xform EXPRESSION
       use sed replace EXPRESSION to transform file names

Using that, you can pass a sed substitution command and change the / to /abc:

tar cf root.tgz --transform 's/^\//\/abc/' /

This will still print / paths when creating the archive but they will become /abc when you extract it.


Another approach, if your tar does not have the --transform option is to make /abc a symlink pointing to / and then tar that:

$ ln -s / /abc
$ tar chf root.tgz /abc

The -h is essential as that is what tells tar to follow links:

 -h, --dereference
       follow symlinks; archive and dump the files they point to

That will have the effect of setting /abc as the top level directory.

3

With GNU tar, you can use that command:

tar --transform="s|/|/abc/|" -Pcf bar.tar /

Otherwise, here is a portable way to do it, i.e. one that doesn't rely on a GNU or other specific tar extension but is based on a POSIX tool that should be available on any Unix compliant machine:

pax -w -s '/\//\/abc\//' -f foo.tar /
1

Here is how I did it which works for tarring from any location (not just /):

tar --transform 's|^|/abc/|' -zcvf /path/to/dest.tgz *

It simply appends a /abc/ to the beginning of every path.

1
  • 1
    When extracting an archive created this way I get a warning tar: Removing leading / from member names. Using 's|^|abc/|' worked well for me. Dec 12, 2019 at 11:15
0

Based on @terdon 's excellent answer, a more "didactic" example...

tar -czf "MY_NEW_FOLDER_NAME.tar.gz" --transform "s/^\.\/MY_FOLDER_NAME/MY_NEW_FOLDER_NAME/" "./MY_FOLDER_NAME"

IMPORTANT: Note that ^\.\/MY_FOLDER_NAME must exactly reflect the path to the target directory "./MY_FOLDER_NAME".

You can play around building your regex: SED compatible online escape character and GNU sed REPL.

Thanks! ✌️😊

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .