Copy file ownership from file to another in Linux

Sometimes you copy some files to a folder full of files owned by another user and you want all the files and folders to belong to one user. Instead of manually copying the user:group names you can pull this information from an existing file or folder. Consider this example:

# touch a b ownerCopiedFromHere
# mkdir dir
# touch dir/c dir/d

# find . -exec ls -ld {} \;
-rw-rw---- 1 root root 0 Sep 27 14:33 ./a
-rw-rw---- 1 root root 0 Sep 27 14:33 ./b
-rw-rw---- 1 root root 0 Sep 27 14:33 ./ownerCopiedFromHere
drwxrwx--- 2 root root 4096 Sep 27 14:33 ./dir
-rw-rw---- 1 root root 0 Sep 27 14:33 ./dir/c
-rw-rw---- 1 root root 0 Sep 27 14:33 ./dir/d

# chown vlatko:vlatko ownerCopiedFromHere dir/c
# find . -exec ls -ld {} \;
-rw-rw---- 1 root root 0 Sep 27 14:33 ./a
-rw-rw---- 1 root root 0 Sep 27 14:33 ./b
-rw-rw---- 1 vlatko vlatko 0 Sep 27 14:33 ./ownerCopiedFromHere
drwxrwx--- 2 root root 4096 Sep 27 14:33 ./dir
-rw-rw---- 1 vlatko vlatko 0 Sep 27 14:33 ./dir/c
-rw-rw---- 1 root root 0 Sep 27 14:33 ./dir/d

# chown -R --reference b *
# find . -exec ls -ld {} \;
-rw-rw---- 1 vlatko vlatko 0 Sep 27 14:33 ./a
-rw-rw---- 1 vlatko vlatko 0 Sep 27 14:33 ./b
-rw-rw---- 1 vlatko vlatko 0 Sep 27 14:33 ./ownerCopiedFromHere
drwxrwx--- 2 vlatko vlatko 4096 Sep 27 14:33 ./dir
-rw-rw---- 1 vlatko vlatko 0 Sep 27 14:33 ./dir/c
-rw-rw---- 1 vlatko vlatko 0 Sep 27 14:33 ./dir/d

As is readily seen from the example above, using:

# chmod -R --reference fileToCopyOwnershipFrom targets

You can copy file ownership recursively from one file or folder to any number of files and folders. If you do not need the recursive option, simply omit the -R switch.

 

 

Your thoughts

No comments

Add comment

* - required field

*




*