fix ownership of users home directories under unix

Posted by david marsh on Mon 14 April 2008

If the users home directories and files gets accidently changed in bulk (eg using a chown -R in the wrong place), this script will change the ownership of their directories and files back to their username and primary group.

One advantage of this script is that if the user name or group can't be found (eg not in the passwd or group files), the default owner or group of the directory or files is changed to root.

for dir in `ls -1 /home` ; do
  user=`id $dir | awk -F [\(\)] '{print $2}'`
  group=`id $dir | awk -F [\(\)] '{print $4}'`
  chown -R $user:$group $dir
done

tags: shell, unix