Home > Software engineering >  how to create a script to check a list of users present in a system
how to create a script to check a list of users present in a system

Time:03-03

I have a list of users in a file ( America, Belgium, India, Srilanka, Bhutan) I need to run a script on each machine to check the above users exist, if its does not, create those users , users are on file resides in /etc/users.txt

Contenets of users.txt

America

Belgium

India

Srilanka

Bhutan

I tried this, but it's not checking users on my list of files.

#!/bin/sh
if grep -q "^$1:" /etc/users ;then
    echo exists
else
    echo FALSE
fi

CodePudding user response:

  1. you didnt call users.txt, you just called users

  2. you have a bunch of incorrect regex in your grep

  3. (optional) you should use -i on grep to accept lowercase letters

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

CodePudding user response:

Use a while loop to read from file:

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
  • Related