0

I have ips file with content:

192.168.10.10 3306
192.168.10.20 3306

and my script is:

1 #!/bin/bash
  2
  3 p=0
  4 cat /root/ips | while read host port
  5  do
  6    check_up=$(bash -c 'exec 3<> /dev/tcp/'$host'/'$port';echo $?' 2>/dev/null)
  7     if [ $check_up != 0 ]
  8         then
  9           p=$[$p+1]
 10           echo "(1):p in loop = $p"
 11     fi
 12         echo "(2):p in loop = $p"
 13  done
 14      echo "(3):p out loop = $p"
 15
 16     if [ $p % 2 != 0 ]
 17        then
 18             exit 1
 19      fi
~

and out put is:

[root@db1 ~]# ./new-script.sh
(1):p in loop = 1
(2):p in loop = 1
(1):p in loop = 2
(2):p in loop = 2
(3):p out loop = 0
./new-script.sh: line 16: [: too many arguments

why echo "(3):p out loop = $p" return 0 (first value $p)!? when last value $p is 2 ? also, how to fix the error in line 16?

pyramid13
  • 639

1 Answers1

2

The standard way to do arithmetic in the shell is $((..)). Standard test/[ supports only comparisons and other tests. So, the standard-conforming version would be:

if [ "$(( p % 2 ))" -ne 0 ]; then...

(That only needs the quotes if your IFS contains digits, so usually they're not needed.)


In Bash/ksh/zsh, you could use the (( .. )) construct, which works like a command and allows the test too:

if (( p % 2 != 0 )); then ...

The [[ test seems to allow some arithmetic, but it's a bit picky about the syntax/whitespace, so you probably shouldn't do that.


As for why the assignment to p doesn't persist outside the loop, see

ilkkachu
  • 138,973