0

I am trying to create a user from a a text file called names.txt

(first and second field will be comment, third field will be username and forth field will be password)

Jessica Brown,jessicabrown,id0001
James Santos,jamessantos,id0002

This is what I have so far, but it is not working and I have a feeling I can do it a shorter way but can't figure it out.

user_name=$(cat names.txt | cut -d, -f3)
password1=$(cat names.txt | cut -d, -f4)
comment1=$(cat names.txt | cut -d, -f1 -f2)

user_name2=$(cat names.txt | cut -d, -f3)
password2=$(cat names.txt | cut-d, -f4)
comment2=$(cat names.txt | cut -d, -f1 -f2)

useradd "$user_name" -p "$password1" -c "$comment1"
useradd "$user_name2" -p "$password2" -c "$comment2" 
10 Rep
  • 2,217
  • 7
  • 19
  • 33
carlos88
  • 29
  • 2
  • Hi, interesting, perhaps split each line into an array of words https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash – IronMan Oct 19 '20 at 21:30
  • What about using ansible, described in https://stackoverflow.com/questions/19292899/creating-a-new-user-and-password-with-ansible – Oliver Gaida Oct 19 '20 at 21:34

1 Answers1

2
  1. To read the file and split the fields you may simply use read-while loop
  2. Check man useradd for proper options for the command

Example (echo is here only for demonstration, remove it in final script):

#!/usr/bin/env bash

while IFS="," read -r COMMENT1 COMMENT2 USERNAME PASSWORD ; do
  echo useradd "$USERNAME" --password "$PASSWORD" --comment "$COMMENT1,$COMMENT2"
done <names.txt
Doj
  • 1,244
  • 6
  • 13
  • 19
  • 2
    The pipeline `cat file | while ...` causes an unnecessary subshell. It is not only inefficient, but hides the variables assigned in the while loop (it doesn't apply in this case). It will be better to say `while ... do; ... done < file`. – tshiono Oct 20 '20 at 01:49
  • Alright I've modified the script with file redirection instead of `cat` as it is more common, although I think scripts with `cat` are more readable and prefer to trade the mentioned side effects for the readability. – Doj Oct 20 '20 at 10:06
  • Thank you for your help. Question, if the password were to have dashes in it for example id-00-01 in the text file, how would I set up the password without the dashes so it be id0001? – carlos88 Oct 21 '20 at 19:35
  • @carlos88 you may just use `"${PASSWORD//-}"` instead of `"$PASSWORD"` – Doj Nov 17 '20 at 01:40