87

I have to compress a directory using tar.gz preserving not only permissions, but ownership/groups too.

And, in this directory there are many files that belong to many users.

2 Answers 2

90

The owners of the file is preserved by default.

When extracting you need to use --same-owner flag. Such as tar --same-owner -xvf file.tar although the flag is only recommended for super users.

Check the tar man page.

8
  • 17
    It has to be tar -cvpf file.tar (or perhaps better yet in terms of clarity, -cvp -f file.tar). Otherwise the -fp part is interpreted as --file p, and tar is writing to the file named p instead of file.tar.
    – KT.
    Apr 29, 2016 at 10:57
  • 13
    Also, given that the answer mentioned compression and people tend to copy-paste answers from posts without thinking anyway, let me note that the popular archiving idiom with compression would be: tar -czvpf file.tar.gz folderToCompress or tar -cjvpf file.tar.bz2 folderToCompress.
    – KT.
    Apr 29, 2016 at 11:00
  • 32
    This answer is wrong. p is an extraction flag, it will have no effect at archive creation. It also affects file permissions, not ownership. The respective flag for ownership is --same-owner, which is enabled by default when extracting as root. Jun 1, 2016 at 11:33
  • 1
    @NVRAM SnowRep undid your changes (!!!). SnowRep, I'm downvoting you and restoring NVRAM's edit, which is correct. Please do not intentionally put incorrect info on the site! Sep 27, 2016 at 23:24
  • 1
    @VladimirPanteleev , you are right. If you ant, you can post a new answer and I'll set it as accepted. Jan 13, 2017 at 12:54
56

I have to compress a directory using tar.gz preserving not only permissions, but ownership/groups too.

By default, tar will preserve file permissions and ownership when creating the archive.

To extract file permissions and ownership, you will need to run tar as root when extracting, since changing file ownership usually requires superuser privileges. See this question for more information.

2
  • 5
    When you say it preserves ownership, does that mean both the user and the group? Aug 1, 2016 at 10:56
  • 8
    That's correct. Both the owner and group are recorded by default (at least in GNU tar). Aug 1, 2016 at 13:26

You must log in to answer this question.

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