-1

I'm trying to add multiple users from a text file and then to a group but I keep getting this error:

'seradd: invalid user name 'srogers

My current script is:

for i in $(cat users.txt)
do
  echo $i
  sudo useradd -m -s /bin/bash -G interns $i
done

What am I doing wrong?

David Foerster
  • 36,890
  • 56
  • 97
  • 151
DJAY
  • 13

1 Answers1

3

You do not give us insights about you particular task and about contents of users.txt file, but I could give a few recommendations that will eliminate simple problems.

First

Always surround all variables with double quotes " in bash scripts. This simple trick help to avoid a lot script problems. In your particular case replace all $i with "$i".

Second

Always add double dash -- at the end of command line to signify the end of command options. It helps to avoid problems when positional parameter has - as a part of its string. Finally the line with useradd command will look like:

$ sudo useradd -m -s /bin/bash -G interns -- "$i"

Third

Consider that usernames should satisfy the constraints. It depends on particular Linux distribution, here is quote from man useradd of Ubuntu 14.04

   It is usually recommended to only use usernames that begin with a lower
   case letter or an underscore, followed by lower case letters, digits,
   underscores, or dashes. They can end with a dollar sign. In regular
   expression terms: [a-z_][a-z0-9_-]*[$]?

   On Debian, the only constraints are that usernames must neither start
   with a dash ('-') nor plus ('+') nor tilde ('~') nor contain a colon
   (':'), a comma (','), or a whitespace (space: ' ', end of line: '\n',
   tabulation: '\t', etc.). Note that using a slash ('/') may break the
   default algorithm for the definition of the user's home directory.

   Usernames may only be up to 32 characters long.

And finally read this to be aware of other common mistakes.

Also take a look to newusers utility, it might be easier if you have tons of users to create.

David Foerster
  • 36,890
  • 56
  • 97
  • 151
c0rp
  • 10,010