Reputation: 91
I have a txt file called Usernames.txt with such information (name followed by group type). E.g. (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.
E.g. 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
Upvotes: 0
Views: 1014
Reputation: 2955
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 (i.e. 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.
Upvotes: 1