3

I want to add a few folders (recursively) to a new tar archive. All of the folders should be at the root level of the resulting archive. Is there any way to add all folders without their parents, and without cd-ing into their directories first and adding them step-by-step?

Consider the following directory structure

.
├── bar
│   ├── bar-file
│   └── barsub
│       └── barsub-file
└── foo
    ├── foo-file
    └── foosub
        └── foosub-file

I'd like to add bar and foosub to a tar archive.

# add folders with different parents
# could be e.g. /some/foo/foosub and /other/bar as well
$ tar cvf archive.tar bar foo/foosub
a bar
a bar/bar-file
a bar/barsub
a bar/barsub/barsub-file
a foo/foosub
a foo/foosub/foosub-file

but what I wanted is

.
├── bar
│   ├── bar-file
│   └── barsub
│       └── barsub-file
└── foosub
    └── foosub-file

Is there any easy way to create such a flat tar archive?

  • Your statement, "All folders should be at the root level of the resulting archive" is at odds with your example. Do you mean that you want each named directory to be at the top level of the tarball? – roaima Jul 17 '15 at 11:45
2

With GNU or FreeBSD tar, you can apply a transformation to file names when adding them to an archive (or extracting them).

tar czf foo.tgz --transform='!^bar/!!' bar/ foo

Portably, you can do the same thing with pax.

pax -w -pe -s'!^bar/!!' foo bar/
-1

tar cvf archive.tar bar -C /path/to/foo/ .

  • there may be some misunderstanding: your code does not add bar, but is not what I meant, anyway: I want to add an arbitrary amount of folders to the archive, while their paths do not nessesarily have any shared subpath. So another example would be a new archive with the folders /tmp/foo, /var/log/bar and /opt/baz. – muffel Jul 17 '15 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.