Issue
I am looking to add multiple users to a UNIX Red Hat system. I am using two text files as sources containing 9 usernames and 9 full names separated individually on 9 new lines.
$U contains usernames.txt, $I contains fullnames to go with the -c command and $Z contains the ending numbers from 1-9 to set the -u ending value. What I hoped the script would achieve is that it would populate the useradd command with the values I outlined to make the useradd command execute adding users with their username, comment field (full name) and an ID value. I used an echo command to test what the output was before actually executing the useradd command part of the script on the system. However, the script actually interpreted the spaces in the fullnamecomment.txt as separate iterations and basically the script prints out the same query 9 times sequentially adding 1 to the -u value.
@Community, can anyone provide any input on optimizing this script or changing my method to add multiple users populating username, comment and ID values within the useradd command?
Thanks.
#!/bin/bash
for U in $(cat username.txt)
do
for I in $(cat fullnamecomment.txt)
do
for Z in {1..9}
do
#useradd $U -m -c $I -u 10010$Z
echo "useradd $U -m -c $I -u 10010$Z"
done
done
done
Solution
When you nest your loops, that means you want to run the inner loop over and over, every time the outer loop happens. That's clearly not what you actually mean to do here; your code is instead intended to iterate over the variables in lockstep, pairing up each username, fullname and UID. That means you should have only one loop instead of nesting multiple loops inside each other.
offset=0
while IFS= read -r username <&3 && IFS= read -r fullname <&4 && (( ++offset )); do
useradd "$username" -m -c "$fullname" -u "$((100100 + offset))"
done 3<username.txt 4<fullnamecomment.txt
Answered By - Charles Duffy