two if conditions in for loop bash scripting

I’ve trying to make two if conditions in for loop. Is it possible this? Now doesn’t return anything from second if only two OK from first if.

#!/bin/bash
servers=("212.39.82.157" "212.39.82.157" "1.1.1.1")

for i in "${servers[@]}"; do

ping -c 1 $i > /dev/null 
  if [ $? -eq 0 ]; then
     echo "OK"  
  fi

  if [ $(netstat -na | grep ':3708' | grep ESTABLISH | wc -l) -eq 2 ]; then
     echo "NOT - OK"
  fi
done

For third IPin the list must return NOT - OK since is not online. But the output is this

root@ubuntu:~$ ./check.sh
OK
OK
root@ubuntu:~$

What I missing here?

UPDATE:

 #!/bin/bash
servers=("212.39.82.157" "212.39.82.157" "1.1.1.1")

for i in "${servers[@]}"; do

ping -c 1 $i > /dev/null 
  if [ $? -eq 0 ]; then
     echo "OK"  
  fi
done
  if [ $(netstat -na | grep ':3708' | grep ESTABLISH | wc -l) -eq 0 ]; then
     echo "NOT - OK"
  fi

If I put it outside for loop it must work?

Asked By: S.I.

||

Put hosts, IP addresses in a file for example.

hosts.txt contains the following

212.39.82.157 
212.39.82.155 
1.1.1.1
22.22.22.22

Create the script.

#!/bin/bash

ping_hosts(){
echo
echo "*** Ping all hosts ***"
echo "--------------------------------------------"

count1=0
count2=0
start=$(date +"%d-%m-%Y-%T")

hosts=( 1.1.1.1 2.3.3.4 4.5.6.6 )

while read -r line
do
#PING=`ping -s 64 $line -c 1 | grep packet | awk '{print $(NF-2)}'`
PING=$(ping -s 64 $line -c 1 | grep packet | awk '{print $(NF-4)}')

if [[ "$PING" == "0%" ]]; then
count1=$((count1 + 1))
printf '%sn' "$line UP" 
else
count2=$((count2 + 1))
printf '%snn' "$line DOWN"
fi
done < <( printf '%sn' "${hosts[@]}")

end=$(date +"%d-%m-%Y-%T")

printf '%sn' "Start:$start"
printf '%snn' "End**:$end"
printf '%sn' "$count1 hosts UP and $count2 hosts down"

}
ping_hosts

Now make the script executable and run it. Probably it defeats the purpose for what you want. Just wanted to share it.

UPDATE your answer

#!/bin/bash
servers=("212.39.82.157" "212.39.82.157" "1.1.1.1")

for i in "${servers[@]}"; do

ping -c 1 $i > /dev/null 
  if [ $? -eq 0 ]; then
     echo "OK"  
  elif [ $(netstat -na | grep ':3708' | grep ESTABLISH | wc -l) -eq 0 ]; then
     echo "NOT - OK"
  fi
done

As a side note, your script is poorly written when it comes to bash syntax.

Answered By: Valentin Bajrami
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.