如何创建脚本来检查系统中存在的用户列表

how to create a script to check a list of users present in a system

我在文件中有一个用户列表(美国、比利时、印度、斯里兰卡、不丹) 我需要 运行 每台机器上的脚本来检查上述用户是否存在,如果不存在,则创建这些用户, 用户在文件驻留在 /etc/users.txt

users.txt

的内容
America
Belgium
India
Srilanka
Bhutan

我试过了,但它没有检查我的文件列表中的用户。

#!/bin/sh
if grep -q "^:" /etc/users.txt ;then
    echo exists
else
    echo FALSE
fi
  1. 你没有打电话给 users.txt,你只是打电话给用户

  2. 你的 grep 中有一堆不正确的正则表达式

  3. (可选)你应该在 grep 上使用 -i 来接受小写字母

    #!/bin/sh
    if grep -i -q "" /etc/users.txt ;then
       echo exists
    else
       echo FALSE
    fi
    

使用 while 循环读取文件:

while read -r line;
do
if id "$line" >/dev/null 2>&1; then
        echo "$line exists"
else
        echo "$line does not exist"
        sudo useradd "$line"
fi 
done < file