IP Address LookUp Bash Script

I am new to bash scripting. I want write a script that reads from the first argument file and run nslookup, then prints out each nslookup. Something like below:

File name = ip

8.8.8.8
8.8.4.4

Bash shell script: nslookup.sh

#!/bin/bash
for i in $1
  do
      nslookup $i
  done

I run the command ./nslookup.sh ip , but doesn't work.

Please let me know what I am doing wrong.

Thank you in advance.

Please use code tags as required by forum rules!

You can't do it like that. $1 will hold the string "ip" if script is called as indicated, and the for loop will execute exactly one single time, $i holding "ip", resulting in nslookup ip which will fail, (almost) certainly.

Try instead in your script:

while read IP
  do nslookup $IP
  done < $1

Thank you for the reply. I will try that will while loop.

If I were to use for loop script, what do you have to read the content of "ip" file?

-BB

If you invoke your script as:

./nslookup.sh ip

$1 inside your script will expand to ip . If you replace the code in your script with the code RudiC suggested, the redirection on the last line will cause the read to grab one IP address from the file ip each time through the loop until all lines have been processed.

Basically, I know how to call a file within a loop script. However, that can be cumbersome if you have multiple IP address groups (or other information) in multiple files. I am trying to avoid modifying the shell script every time I have to lookup different files. I would like to learn if I can do this by giving it an argument , so I can avoid modifying the script each time.

Is there a way to do this by giving it an argument when you run the script?

I repeat, if you put the code RudiC gave you in your script, and invoke it with:

./nslookup.sh ip

your script will lookup all of the IP addresses listed in the file named ip .
If you invoke it with:

./nslookup.sh SomeOtherFile

your script will lookup all of the IP addresses listed in the file named SomeOtherFile .

Please explain how this is different from what you have said you want to do???

My apologies. I thought the "ip" portion was a file name. It works just as you said. Thank you!

You could also use xargs:

$ xargs -n1 nslookup < ip