简体   繁体   中英

how to add multiple users and afterwards add them to groups in linux using bash script

I have a txt file called Usernames.txt with such information (name followed by group type). Eg (These are the few instances as there are way more inputs.)

Usernames.txt:

ellipsiscoterie,visitor
magnetcommonest,visitor
belateddefensive,staff
wizardmeans,visitor
bobstercaramelize,staff

In the script show below, I attempted to add each line's name as a user and allocate each new user to its respective groups. However I have encountered this error. And the output is not what I had in mind. I hope someone can help me out, thanks.

Basically this is what I want to do but for every single lines in the txt file. Eg sudo useradd bobstercaramelize (which is the name of user) and sudo usermod -a -G staff bobstercaremelize .

Error:

createUsers.sh: line 4: $'[visitor\r': command not found

Code:

#!/bin/bash 
while read line; do
arrIN=(${line//,/ })
if [${arrIN[1]} = "visitor" ]; then
  sudo useradd ${arrIN[0]}
  sudo usermod -a -G  visitors ${arrIN[0]}
else
 sudo useradd ${arrIN[0]}
 sudo usermod -a -G staff ${arrIN[0]}
fi
done < Usernames.txt

First, the error seems to stem from a missing space: [${arrIN[1]} = "visitor" ] needs to be [ ${arrIN[1]} = "visitor" ] . Note the space between [ and ${arrIN[1]} .

Second, the \\r in the error message indicates that there might be an issue with the line endings of your Usernames.txt file. Try to save it with Unix/Linux line endings (ie each line should be terminated by \\n only).

Third, you might want to consider parsing the file's contents differently:

while IFS=, read user group; do
    if [ "${group}" = "visitor" ]; then
        sudo useradd "${user}"
        sudo usermod -a -G  visitors "${user}"
    else
        sudo useradd "${user}"
        sudo usermod -a -G staff "${user}"
    fi
done < Usernames.txt

This way, read does the splitting for you, making things easier, more precise and more readable. I also added double quotes where advisable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM