I need to use the tar command to unpack a .tar.gz file and I need to do it from root but when the files unpack I want them to be owned by a specific user, not the root user. Can someone give me a hand?. I found the man pages confusing.

The easiest is probably to use chown to change the owner of the directory after you've extracted it. And you can use chmod too to remove some permissions for group and others too.

Let's say you have the file my_archive.tar.gz which contains a top-level directory called my_folder, and the user you want to make the owner of the folder is called "myself". Then, you can do this:

$ sudo su
# tar -xzf my_archive.tar.gz
# chown -R myself my_folder
# chmod -R go-w my_folder
# exit
$

This goes into superuser mode. Extracts the archive into the current directory (use cd to navigate to where you want to extract it first). Changes the ownership recursively (-R) to the user myself. Changes the access permissions recursively such that write access is removed from the "group" and "others", such that the read and execute permissions are preserved, and all permissions are preserved for the owner. Finally, it exits the superuser mode (you don't want to stay in that mode any longer than you need to).

You can use sudo to do this, as in "sudo userid tar -zxvf filename.tgz".

If you have the permissions on the files set properly when they are put into the tar.gz archive then:

sudo tar -xpvzf filename.tar.gz

Will A: Ensure that it is run as root, B: Preserve the permissions of the files to the same as when compressed, and C: make like 100000x easier.

also, typically for linux you can do

somecommand --help

which will list all the available options for any 'somecommand' may seem overwhelming at first but I am sure you'll have it all figured out in no time.

on a sidenote. I use linux as my main computer 24/7, I have done so for over a year now. I dont remember 90% of the commands/options available on my machine at any given time, but I do remember some key tricks like tab complete, or double tabbing for all available commands,... etc. Most people dont remember off by heart every linux utility they use, and we don't expect you to either ;)

FWIW, when root untars a tar file, the files extracted should get the ownership and permissions of the original owner, as stored in the archive. If the original owner doesn't exists on the new system, or has a different UID, then it may appear that the files are owned by another user, or by a UID (User ID) that doesn't exist yet on the new system, such as 5001 instead of "Fred Flintstone".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.