Linux – Packaging with tar

linuxtar

I am trying to package the files:

file1
folder2/hello
folder2/world
file3

into a tar file so they are encapsulated in a custom defined folder, so the tar -tvf archive.tar appears as:

mycustomfolder/file1
mycustomfolder/folder2/hello
mycustomfolder/folder2/world
mycustomfolder/file3

Currently to come around this I am:

  • Creating an archive(x) of file1, folder2 and file3.
  • Creating a mycustomfolder folder.
  • Extract the archive(x) into mycustomfolder
  • Create an archive(y) from mycustomfolder

I can't help it think their might be one step of doing this or a better way?

Best Answer

If you want the archive to extract into its own directory -- which is generally better, since ones that don't can make a mess -- just create the directory, then move/copy the content tree into it, so you have, as in your second example:

mycustomfolder/file1
mycustomfolder/folder2/hello
mycustomfolder/folder2/world
mycustomfolder/file3

Then tar -cvf myarchive.tar mycustomfolder. To extract, tar -xvf myarchive.tar.

If you don't want to create the directory first, you can transform the files names and append a directory prefix:

tar --xform="s%^%mycustomfolder/%" -cvf myarchive.tar file1 folder2 file3

The transformation (see man tar) uses sed syntax; I used % instead of / for the divider because s/^/mycustomerfolder\// creates a folder named mycustomfolder\ (== odd behavior IMO), but s/^/mycustomfolder// is (properly) an "Invalid transform expression".

Related Question