0

I have 2 text files, users.txt with a list of 1000 users and groups.txt with a list of 50 groups. I want to run a command that adds 30 users to each group (ex: users 1-30 to group 1, users 31-60 to group 2, etc.). What would be the most practical way of doing this?

This is what I have so far:

for i in `cat users.txt` ; do useradd $i; echo Pass$i | passwd $i -- stdin; done
for i in `cat groups.txt` ; do groupadd $i; done
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
greglorious_85
  • 71
  • 2
  • 15
  • You will get better help if you show what you have done so far, and explained the specific problems you are having. Please read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – glenn jackman Jan 23 '19 at 15:34

1 Answers1

1

Assuming your files have one user and one group per line, here's a pseudo-oneliner:

sed = groups.txt | while true ; do 
  read line_no
  read group_name
  [ -z $line_no ] && break
  (( from = (line_no - 1) * 30 + 1 ))
  (( to = line_no * 30 ))
  sed -n "${from},${to} p" users.txt | xargs -r -n 1 usermod -a -G $group_name 
done

This code calls sed(1) to print line number (starting with 1) and the line itself (i.e. the group name) for each line in groups.txt, then pipes that output into an endless loop, which does the following:

  • Reads line number from the piped input into $line_no variable
  • Reads group name from the piped input into $group_name variable
  • If $line_no is empty, assumes we've reached an end of groups.txt and break-exits the loop
  • Calculates starting and ending line numbers for users.txt using $line_no as index
  • Calls sed(1) to print all lines from users.txt between those lines
  • That list of usernames is piped into xargs(1), which runs usermod(8) for each single username, appending it to a $group_name from above. '-r' switch tells xargs(1) to not run usermod(8) if the username/stdin is empty.

edit: replaced semicolons with line breaks for legibility

KMZ
  • 463
  • 3
  • 12
  • This is exactly what I was looking for. Thank you. Just to be clear though, if I want to set passwords to each user, should I run the commands I already have (in my edits to the original post) or is there a way to assign a password (could be random) in this script? – greglorious_85 Jan 23 '19 at 15:45
  • Use [this comment](https://stackoverflow.com/questions/2150882/how-to-automatically-add-user-account-and-password-with-a-bash-script#comment39304417_2151149) to change passwords non-interactively. – KMZ Jan 23 '19 at 15:50