Using multiple 'for' statements

Hello,

I am new to scripting and I am trying to write a simple script that creates users and adds their passwords from two files; one a user list file and another a password list file.

For example, I have two files already.

$ cat file1
andy
stephane
aby
paul
$ cat file2
123
234
324
456

Is it possible to write a bash script with for statement such as:

for i in $(cat file1) j in $(cat file2); do useradd $i; echo $j | passwd   --stdin $i; done

My ultimate end goal is that the script will take the string in the first line of file1, create a user based on that name, then use the same line of file2 as the password input, then repeat with next line, creating all four users.

And I have no idea how to make this work without next for loops (which is not giving me the desired results).

Not sure if there is a better way apart from using the for command too.

Thank you.

Femo

There are a number of ways to accomplish that. Assuming there is a direct one-to-one mapping between the two input files, then you could do something like:

paste file[12] | while read user pass x; do
  useradd "$user"
  echo "$pass"| passwd --stdin "$user"
done

(not tested, and it would make sense to add some handling in case a user exists, etc. Additionally, should your usernames (heaven forbid!) or password have whitespaces, then you might need to use a delimeter with the paste command, and use IFS=... between the while and read (and remove x, which is only used to ensure any junk after pass is removed))

2 Likes

Hello @scott,

Thanks a lot. I did try to run this on my timeline using different commands and to see how this will work.

$ paste file[12] | while read user pass x; do
> echo $user
> echo $pass
> done
andy
123
stephane
234
aby
324
paul
456

Works like a charm.

I will incorporate the idea into my script now.

much appreciated.

regards,
Femo

Without an external command (paste)

while read i <&3 && read j <&4
do
  useradd "$i"
  echo "$j" | passwd --stdin "$i"
done 3<file1 4<file2
3 Likes

thanks once again Scott!

------ Post updated at 12:48 PM ------

@MadeInGermany

Thanks for this too. I actually think this is a neater way to approach it without using additional commands. I will find a way to use this and Scotts thoughts earlier on user already existing and whitespaces.