Home
 

Archive for the ‘Linux Tips’ Category.

Easily Set Home Directory Ownership for Multiple Users In Linux Using This Shell Script

 

Today I was in a situation where I had over 300 home directories that had been copied from an older Linux machine. The user accounts had already been created on the new machine using Webmin’s batch account creation feature, but were not loaded using the same UID as the original server. Fortunately the home names did reflect the user name, as I was able to use this little bit of shell command line to set the ownership of each home directory to the newly created accounts.


#!/bin/bash
cd /home
for user in `ls -1`;
do chown -R $user $user;
done


You could also set group ownership, as well as permissions at the same time. This little bit of code will obtain the name of each directory within the /home directory and assign it as the variable $user. It then recursively chowns each directory to the user with the same name as of the directory. If your directory contained three home folders for mark, joe and sam, the script would do this.
chown -R mark mark
chown -R joe joe
chown -R sam sam

You could use this same loop to set permissions, chgrp (group ownership), move or rename directories and so on. Its simple, yet very handy at times. Once again the command line proves more powerful than the GUI in Linux! Since this was my first Linux post I thought I would post something quick and easy, but very handy just the same (for me anyhow). I hope that someone else in a similar situation may find this useful also.

Bookmark and Share: