Unix / Linux: Change File Owner from One User to Another

Objective: Change ownership of all files belonging to a given user, within a targeted directory, to another specified user on Unix / Linux.

On Linux, changing ownership of files from one user to another user is fairly easy. It can be accomplished using the GNU chown utility with the “--from” option.

For example, if you want to change the ownership of all files (including sub-directories) from user foo1 to user foo2, use the following syntax.

# chown -R --from=foo1 foo2

The above syntax will preserve the group ownership. Only the file ownership will be changed.

You are also able to match an existing username and group. So, if you just want to change the ownership of all files belonging to user foo1 and group bar1 and not touch other files, use the following syntax. It will change all files belonging to user:group foo1:bar1 to user:group foo2:bar2.

# ls -l
total 0
-rw-r--r-- 1 foo1  bar1  0 Nov 14 15:55 file1
-rw-r--r-- 1 foo1  staff 0 Nov 14 15:55 file2
# chown -R --from=foo1:bar1 foo2:bar2 *
# ls -l
total 0
-rw-r--r-- 1 foo2  bar2  0 Nov 14 15:55 file1
-rw-r--r-- 1 foo1  staff 0 Nov 14 15:55 file2

You can see that, only the file “file1” matched the user:group permissions of “foo1:bar1” and therefore only the ownership of that file got changed.

On UNIX systems where the chown utility does not support the “-from” option, we will need to use the find command to sort of emulate the “–from” option. To change all files belonging to user:group foo1:bar1 to user:group foo2:bar2 by using a combination of find and chown commands, use the following syntax.

# find . -user foo1 -group bar1 -exec chown foo2:bar2 {} \;

An alternative command using find, xargs and chown would be:

# find . -user foo1 -group bar1 | xargs chown foo2:bar2

If you are using the find command, you will not need to use the “-R” (recursive) option for chown.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, perl, php, python, java, javascript, nodejs, angular, react); plays_on(xbox, ps4); linux_desktop_user(true); }