I can preserve ownership of folderB and all files and folders inside when creating and extracting a tar file as follows:

tar -cpf out.tar folderA/folderB
sudo tar -xpf out.tar --same-owner

However, folderA is owned by root when extracting unless the folder already exists. Is there any way to preserve ownership of the entire folder hierarchy with tar?


This happens because

tar -cpf out.tar folderA/folderB

doesn’t store folderA as a separate object in the tarball, so it doesn’t have any way of recording the ownership and permissions of folderA.

To preserve the ownership, you need to tell tar to do so when you create the tarball; with GNU tar at least, the following works:

tar -cpf out.tar --no-recursion folderA --recursion folderA/folderB

This stores folderA (and its permissions etc.) without recursing, and folderA/folderB with its contents.

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.