0

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
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 1
    Does this answer your question? [Are shell scripts sensitive to encoding and line endings?](https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings) – Jetchisel Oct 18 '21 at 08:40
  • 2
    @Jetchisel: imo only partially a duplicate due to the missing space. – Fonic Oct 18 '21 at 09:27

1 Answers1

1

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.

Fonic
  • 2,625
  • 23
  • 20