I have a list of users I want to add as users to my server (userlist.txt).

I want to add them using useradd and include their name as a comment

so... every line of the file contains something like this:

vno572,2548,veronica norena,cornerstone group,user,4331,1872,49:46

I want to grab "vno572" + "veronia norena" and add the user like this:

useradd vno572 -c "veronica norena" 

I need to iterate through the whole file and add each user in each line.

I have this so far:

cat userlist.txt | while read line 
  echo $userid
  userid=’cut -d ‘,’ -f 1 userlist.txt’ 
  echo $name
  name=’cut -d ‘,‘ -f 3 userlist.txt’
  useradd $userid -c “$name”  
awk -F, 'BEGIN { OFS=FS } { print $1, $3 }' userlist.txt |
while IFS=, read username realname; do
    useradd -c "$realname" "$username" 

The awk above will pick out the first and third column out of the supplied file and create a comma-separated list of username followed by real name.

The comma-separated output from awk is read, split on commas, and stored in the shell variables username and realname, and useradd is invoked.

Usually when one creates a user, one may want to add a home directory for them at the same time. Do this by adding -m to the invocation of useradd. If the users should be part of a particular group or have secondary groups, use -g and -G with other pieces of info from the input data.


Try with this one, not tested yet:

cat userlist.txt|awk -F',' '{print $1" "$3}'|while read var1 var2;
useradd $var1 -c "$var2"

Hope it work :)


Using awk only:

awk -F, '{ system(sprintf("useradd %s -c \"%s\"", $1, $3)) }' userlist.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.