2

I have 20 users by name user1,user2,user3....user20. I now want to add a directory new_dir to the home directory each of these users .

I’m able to do this by logging in into each user one at a time and creating the directory . But since the number is large , it consumes a lot of time .

Is there a way like for loop or some tools to help with this ?

I’m currently on another user , which is not related to the 20 users in anyway(groups etc)

Deeraj Theepshi
  • 183
  • 3
  • 10

1 Answers1

0

Something like this should work.

Script iterates everything in /home, processes all the the directories but skips lost+found (add others if needed). continue is there for your safety, remove it once you understand the script and have modified it suit your needs.

You should consider the rights and ownership for the created dirs, this script gives the ownership to the user (whatever stat -c "%U" gives) and leaves the group to root (use stat -c "%G" for that).

cd /home                                    # or whatever your home path
for d in *                                  # iterate everything
do 
  if [[ -d "$d" && "$d" != "lost+found" ]]  # process dirs but not lost+found
  then                                        # add others if needed
    echo Processing "$d"
    continue                                # REMOVE WHEN YOU UNDERSTAND THE SCRIPT
    continue                                # ARE YOU SURE
    continue                                # THIS IS YOUR LAST WARNING
    u=$(stat -c "%U" "$d")                  # get user of each dir
    mkdir -p "$d"/new_dir                   # creat the dir regardles if exists
    chown "$u" "$d"/new_dir                 # set ownership to rightful owner
  fi                                          # consider setting group ownership
done
James Brown
  • 36,089
  • 7
  • 43
  • 59