83

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.

Paulo Coghi
  • 1,174
  • 1
  • 11
  • 14

2 Answers2

87

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.

Steve Ward
  • 233
  • 2
  • 4
SupaJord
  • 1,201
  • 10
  • 7
  • 16
    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
  • 11
    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 09 '16 at 17:38
  • 29
    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 01 '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
  • @VladimirPanteleev , you are right. If you ant, you can post a new answer and I'll set it as accepted. – Paulo Coghi Jan 13 '17 at 12:54
  • To extract with `--same-owner` you need to be root. And `--same-owner` also affects the `t` command. And about `-fp` being interpreted as `--file p`, in [traditional style](https://man.archlinux.org/man/core/tar/tar.1.en#Option_styles) you first specify options (single letters), then arguments. So `tar cvfp file.tar...` would make it create `file.tar`, not `p`. – x-yuri Dec 20 '21 at 08:35
52

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.

Vladimir Panteleev
  • 1,389
  • 1
  • 13
  • 20