0

I have a particular use case, where I want to extract a tar archive (as root) and intentionally overwrite some destination file(s) with the contents of the archive. This is all fine and easily achievable, but I also want to retain the original ownership and permissions of the original destination file(s). As an example:

$ touch file && tar cf test.tar.gz file && sudo chown www-data:www-data file && sudo tar xf test.tar.gz && ls -l file -rw-r--r-- 1 tim tim 0 May 1 11:26 file

Here I create a file as my user (tim:tim), archive it, change its ownership to www-data:www-data, then (as root) extract the archive, overwriting the original file. As you can see, its ownership has been modified to that of the file in its pre-archived state, whereas post extraction, I want it to be owned by www-data:www-data.

I've had a fairly close look at the tar man page, but can't see an immediately obvious way to do what I want. Am I missing anything?

1 Answer 1

0

As a normal user, you wouldn't be able to overwrite the file owned by www-data with only write permissions for the owner, so what you want couldn't work in your example.

What would work, if your user is permitted to write to these files, is to use --overwrite. However you will get errors when tar tries to change the modification time and permissions of the file, because again you as a regular user aren't permitted to do that to files that don't belong to you.

6
  • (Good point, I should have a sudo on the tar xf too. I was doing the test in a directory I owned, so this wasn't necessary.)
    – Tim Angus
    May 1, 2019 at 12:17
  • I'm not sure I see how --overwrite helps here. Overwriting the file isn't the problem; that happens by default. What I'm trying to avoid is that the overwrite changes the metadata of the extracted file to those that are stored in the archive, whereas I want to retain the metadata of the file before it was overwritten. Ultimately I can come up with some elaborate solution that saves the file's metadata pre-extract, and restores it post-overwrite, but I was hoping I could get tar to do that for me.
    – Tim Angus
    May 1, 2019 at 12:17
  • Without --overwrite it will replace the file, i.e. first removing it and thus losing the current owner. But maybe you're better off using pax instead of tar
    – wurtel
    May 1, 2019 at 14:26
  • Ah, that's a subtlety I hadn't appreciated. I had not heard of pax before; I'll give it a look. Though one of the issues in my particular situation is that I am (fairly safely, one would think) assuming tar is available on the machines on which the script will execute. Is pax as widely deployed?
    – Tim Angus
    May 1, 2019 at 14:59
  • pax might not be installed by default but it should be readily available from whatever distribution you use.
    – wurtel
    May 2, 2019 at 6:48

You must log in to answer this question.

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