如何在多个用户的家创建一个目录?

How to create a directory in the home of multiple users?

我有 20 个名为 user1、user2、user3....user20 的用户。我现在想在每个用户的主目录中添加一个目录 new_dir。

我可以通过一次登录每个用户并创建目录来做到这一点。但由于数量大,耗费的时间也很多。

是否有类似 for 循环的方法或一些工具来帮助解决这个问题?

我目前在另一个用户上,无论如何(组等)与 20 个用户无关

像这样的东西应该有用。

脚本迭代 /home 中的所有内容,处理所有目录但跳过 lost+found(如果需要添加其他)。 continue 是为了您的安全,一旦您理解了脚本并根据您的需要对其进行了修改,请将其删除。

您应该考虑创建的目录的权利和所有权,此脚本将所有权授予用户(无论 stat -c "%U" 给出什么)并将组留给 root(为此使用 stat -c "%G") .

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