On my Ubuntu server there are about 150 shell accounts. All usernames begin with the prefix u12.. I have root access and I am trying to copy a directory named "somefiles" to all the home directories. After copying the directory the user and group ownership of the directory should be changed to user's. Username, group and home-dir name are same. How can this be done?
2 Answers
Do the copying as the target user. This will automatically make the target files. Make sure that the original files are world-readable (or at least readable by all the target users). Run chmod
afterwards if you don't want the copied files to be world-readable.
getent passwd |
awk -F : '$1 ~ /^u12/ {print $1}' |
while IFS= read -r user; do
su "$user" -c 'cp -Rp /original/location/somefiles ~/'
done
-
+1 for using getent. unlike grepping /etc/passwd, it works with any and all Name Service Switch compatible password database(s) in use on the system, incl. /etc/passwd, ldap, mysql, pgsql, extrausers, db, and others.– casCommented Sep 22, 2012 at 3:41
$ basename -a /home/* | xargs -rI{} sudo rsync -a --chown {}:{} somefiles/ /home/{}/
Explanation
basename -a /home/*
selects all users' home directories and strips their name of the path.
xargs -rI{}
executes the following command separately for each entry on standard input and substitutes {}
with the text of the entry (user's directory in our case).
rsync -a --chown {}:{} somefiles/ /home/{}/
copies your somefiles/
directory to the home directory of the user and replaces owner and group with the user's name.