Isla Isla - 4 months ago 18
Bash Question

Bash Script: for loops, read, arrays, compare two files

I'm trying to do something like this.

I need every entry/user in

file1
to be queried against every entry in
file2
independently.

> cat file1
john
james
mark
adam
luke
chris
scott

> cat file2
check if **user** has account
check if **user** has permission
check if **user** has website
check if **user** has root


So basically read line from
file1
one by one, but execute against all entries in
file2
. So john is checked against all four entries, then james and so on.

Do i assign variables to every user? then how will I define that them in
file2
also the lists/files are likely to fluctuate in content/size so would like to accommodate that change..

Thanks guys!
Isl

Answer

Put the collection of commands that you need to run for each word from the first file into a script, read the file with words line by line and execute the commands for the currently read word:

while read -r word; do
   some command using "$word"
   some other command using "$word"
   # etc.
done <file_with_words

What's basically happening here is that I'm asking you to turn your second file into a script with a loop.

As per your comment, the first file actually contains hostnames, and the second file contains commands to run against those hostnames. What you're asking in the question is to create and execute a new script for each hostname in the first file. This makes little sense as the script is, well, already a script (it also sounds terribly fragile and might pose a security risk if the input is not properly handled). Instead, modify it to read in the hostnames as per my code above.