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.
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))
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.