31

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.

31

You're looking for the -p flag so an example would be tar -cvpf file.tar folderToCompress, be careful using the tar command as it is easy to overwrite files if your syntax for the command is incorrect.

The owners of the file is preserved normally, 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.

  • 7
    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 '16 at 10:57
  • 4
    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 '16 at 11:00
  • @KT - you are correct, so I fix the -f flag -- although I didn't fix the compression -z flag. For compression, I'd recommend -Ipigz (that's a capital i) in lieu of -z; on multi-core systems, pigz can be considerably faster. – NVRAM May 9 '16 at 17:38
  • 8
    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. – Vladimir Panteleev Jun 1 '16 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! – Kyle Strand Sep 27 '16 at 23:24
17

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.

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

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.