Isla Isla - 1 year ago 79
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

to be queried against every entry in

> cat file1

> 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
one by one, but execute against all entries in
. 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
also the lists/files are likely to fluctuate in content/size so would like to accommodate that change..

Thanks guys!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download