Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am new to unix. I want to write a script to change the ownership of files from root to myuser. Script which will check the ownership and if found as root will change it to myuser. The script should also log errors to a file. I know how to change ownership of files but not sure about putting the same in a script Please help.

share|improve this question
    
Is this all the files in a particular directory? –  Graeme Mar 3 at 11:37

2 Answers 2

Assuming you also want to change the group of the file (if not just drop the :newuser).

find /dir/with/files -type f -user root -exec chown newuser:newuser {} + 2>>logfile

Obviously to alter files own by root, you need to be root, so remember to run with sudo or after an su. Also if you want to do directories as well (I imagine you probably do), just drop the -type f.

share|improve this answer

The simplest way of doing this recursively with find (finds files in directory structure that match various parameters). For instance

find . [or other directory] -type f -user 0 -exec chown <newusername> '{}' +

where -type f is used to avoid touching directories or other non-regular types of files (remove if not needed).

Of course you will need to be root to do this. You can just pack this up into a script, as

#!/bin/sh
if [ "$#" -lt 1 ]; then #check if username was given
  echo >&2 "provide user name"
  exit 1
fi
find . -type f -user 0 -exec chown "$1" '{}' +

I don't think you will need to check for different errors - mostly it will just fail if you are not root.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.