Markus84612
Markus84612

Reputation: 311

How to create a tar archive from an absolute path and package files as if they were relative?

On Linux, I am trying to create a .tar.gz archive from a different directory, that is I have a bash script that will be executed from a different directory. The script will package the folder, I will give the absolute directory of the folder say /home/user1/Documents/folder1 however when it packages the tar file, it puts the entire absolute directory in the archive, whereas I only want the relative one from folder1.

For example:

tar czf /home/user1/Documents/folder1.tar.gz /home/user1/Documents/folder1

This will create an archive but where the first folder will be home and then inside that user1 inside that documents and inside that the folder1, no other subfolders from other branches of course.

Also the console gives this error:

tar: Removing leading `/' from member names

I want it to be packaged as if I would execute the command from the same folder, so the only folder in the archive should be folder1, and inside that it's own subfolders.

So the archive inside should look just as if I would have executed this code from the same directory folder1 is in:

tar czf folder1.tar.gz folder1

Upvotes: 3

Views: 6801

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52112

You can use the -C option to change the directory before performing any operations:

tar czf /home/user1/Documents/folder1.tar.gz -C /home/user1/Documents folder1

Now, the contents of your archive will look like this:

$ tar tf /home/user1/Documents/folder1.tar.gz 
folder1/
folder1/file1

The message you get is not an error, by the way. It's tar telling you that it made the paths in the archive relative so as to avoid overwriting files, which could easily happen when unpacking an archive with absolute paths. You can turn off the leading slash removal with -P, but you often don't want that.

Upvotes: 8

Related Questions