首页 > 解决方案 > 如何在多个用户的家中创建目录?

问题描述

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

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

有没有像 for 循环这样的方法或一些工具来帮助解决这个问题?

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

标签: linuxbashubuntu-16.04file-permissionssystem-administration

解决方案


像这样的东西应该工作。

脚本迭代 中的所有内容/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

推荐阅读