File owner after extract changes to irrelevant user in Ubuntu

This is my topology:

My laptop ==> Ubuntu Desktop
| | |
User: root & saeed

My server ==> Ubuntu 20.04
| | |
Users: root & ubuntu (I deleted it as I explain below)

The steps:

  1. I run tar zvcf back.tar.gz . in my laptop with user saeed and file is created.
  2. I upload this file via SFTP to my server by using root user in path example /home/test which is not any user's home dir.
  3. I extract back.tar.gz in /home/test but I see all of the files and directories' owner are ubuntu:ubuntu.
  4. I deleted ubuntu user and tried the third step but got the same result.
  5. I extracted back.tar.gz in my laptop in another path, but all files' owners are saeed:saeed.

Why does this happen?


Solution 1:

When extracting as root, tar by default preserves the original owner ID. User saeed happens to have the same ID as ubuntu on the other computer (and it's probably 1000). You can check IDs by running id saeed, or just id to check the current user.

If you don't want to preserve user ID, either don't extract as root or use the --no-same-owner option. Relevant fragment from the manual:

       --no-same-owner
              Extract files as yourself (default for ordinary users).

The opposite can be achieved for regular users with --same-owner.

Related options --owner and --owner-map can be used when creating an archive:

       --owner=NAME[:UID]
              Force NAME as owner for added files.  If UID is not
              supplied, NAME can be either a user name or numeric UID.
              In this case the missing part (UID or name) will be
              inferred from the current host's user database.

              When used with --owner-map=FILE, affects only those files
              whose owner is not listed in FILE.

       --owner-map=FILE
              Read owner translation map from FILE.  Empty lines are
              ignored.  Comments are introduced with # sign and extend
              to the end of line.  Each non-empty line in FILE defines
              translation for a single UID.  It must consist of two
              fields, delimited by any amount of whitespace:

              OLDUSR NEWUSR[:NEWUID]

              OLDUSR is either a valid user name or a UID prefixed with
              +.  Unless NEWUID is supplied, NEWUSR must also be either
              a valid user name or a +UID.  Otherwise, both NEWUSR and
              NEWUID need not be listed in the system user database.

              As a result, each input file owned by OLDUSR will be
              stored in archive with owner name NEWUSR and UID NEWUID.