Change file ownership, based on previous owner

chownfilesrecursiveusers

I am a moderately new linux user. I changed my PC, and started using CentOS 7 from CentOS 6.

So I attached my previous hard disk to my new pc to take backup of my files. Now, copying the files (and preserving the permissions and all), the files shows owner as 500 (I guess this is my previous UID).

Is there any way I can change them to my new user name? I want to exclude the files which shows some other owners like 501.

Edit:

Example:

ls -l
total 3
-rw-rw-r--.  1 500 500        210 Jan 10  2012 about.xml
drwxr-xr-x.  2 500 500       4096 May 15  2013 apache
drwxrwxr-x.  2 500 500       4096 Dec  9  2012 etc

Now, I can do chown -R xyz:xyz . to make them look like:

ls -l
total 3
-rw-rw-r--.  1 xyz xyz        210 Jan 10  2012 about.xml
drwxr-xr-x.  2 xyz xyz       4096 May 15  2013 apache
drwxrwxr-x.  2 xyz xyz       4096 Dec  9  2012 etc 

But I just want to know if there are some kind of commands which can map user 500 to user "xyz".

Thank you.

Best Answer

If I understand you correctly, you want to change the owner of all files inside some directory (or the root) that are owned by user #500 to be owned by another user, without modifying files owned by any other user. You're in that situation because you've copied a whole directory tree from another machine, where files inside that tree were owned by many different users, but you're only interested in updating those that were owned by "your" user at the moment, and not any of the files that are owned by user #501 or any other.

GNU chown supports an option --from=500 that you can use in combination with the -R recursive option to do this:

chown -R --from=500 yourusername /path/here

This will be the fastest option if you have GNU chown, which on CentOS you should.

Alternatively can use find on any system:

find /path/here -user 500 -exec chown yourusername '{}' '+'

find will look at every file and directory recursively inside /path/here, matching all of those owned by user #500. With all of those files, it will execute chown yourusername file1 file2... as many times as required. After the command finishes, all files that were owned by user #500 will be owned by yourusername. You'll need to run that command as root to be able to change the file owners.

You can check for any stragglers by running the same find command without a command to run:

find /path/here -user 500

It should list no files at this point.


An important caveat: if any of the files owned by user #500 are symlinks, chown will by default change the owner of the file the symlink points at, not the link itself. If you don't trust the files you're examining, this is a security hole. Use chown -h in that case.

Related Question