-1

Verify if base machine IP is present in file

Trying to resolve it using for loop with if condition

#!/bin/bash
#file with IP List /tmp/ip_list.txt
curr_ip="$(hostname -I)"
for n in `cat /tmp/ip_list.txt`; 
do 
  if [ "$n" == "$curr_ip" ]; then
    echo "success"
  else
        echo "fail"
  fi
done

By default it is running else condition.

norok2
  • 25,683
  • 4
  • 73
  • 99
SAM
  • 118
  • 1
  • 11
  • If the `ip_list.txt` file contains line-by-line data, you might be better off using `grep` to find if a given IP appears in the file. – Lix Aug 21 '19 at 12:53
  • 1
    What is the format of `/tmp/ip_list.txt`? What happens if, inside of your `for` loop, you echo out the values of `$n`? – jasonmclose Aug 21 '19 at 12:53
  • it has IP in below format: x.x.x.x x.x.x.x – SAM Aug 21 '19 at 12:55
  • Please [edit] your question instead of adding information in a comment. To debug your code you could print `$n` and `$curr_ip`, preferably with some special characters before and after it, e.g. `echo "n <$n> curr_ip <$curr_ip>"` – Bodo Aug 21 '19 at 12:57

1 Answers1

0
#!/bin/bash

curr_ip="$(hostname -I)"

output=$(grep -c /tmp/ip_list.txt)

if [ "$output" != "0" ]
then
   echo "success"
else
   echo "failure"
fi 

The -c option in grep gives you a count. If it doesn't equal zero, it found something.

jasonmclose
  • 1,667
  • 4
  • 22
  • 38
  • Instead of reading the output of `grep` I suggest to use its exit code to distinguish between found and not found. `if fgrep "$curr_ip" /tmp/ip_list.txt > /dev/null ; then echo success; else echo failure; fi` – Bodo Aug 21 '19 at 13:01
  • Yup. This works as well. I often use the -c because I may want to have a conditional if it finds more than one. – jasonmclose Aug 21 '19 at 13:03
  • I want to exec some command if say [[ 10.10.10.10 == 10.10.10.10 ]] then echo success; else echo fail; fi – SAM Aug 21 '19 at 13:49
  • I think that does not work for IP range it always return fail response: if fgrep "$(hostname -I)" /tmp/ip_list.txt > /dev/null ; then echo success; else echo failure; fi ip_list.txt: 10.10.10.10 10.10.10.11 hostname -I --> 10.10.10.11 – SAM Aug 21 '19 at 14:01
  • @SAM All your explanations or additional information should be added **to the question**. It is difficult to read code snippets in comments, and you cannot correctly format multiline data. Write all this with correct formatting in your question. – Bodo Aug 21 '19 at 15:28
  • I agree with @Bodo. @SAM, you need to both format your comments, but also explain what is going on. `hostname -I` can return multiple IP addresses. Is that what it is doing? Your responses don't have any depth. The amount of work you put into your comments will usually result in an equivalent depth in a response. Where in your original question did you say you needed something to work with an IP range? That is a whole new issue. – jasonmclose Aug 22 '19 at 12:27