M2201
M2201

Reputation: 97

Connectivity test using bash and curl

I am trying to write a script to test if my firewall is blocking multiple pages. When I try to read one or multiple lines from command line I get a -ne: unitary operator expected error.

This is my attempt:

sh test www.3232.com.pe
www.3232.com.pe
test: line 7: [: -ne: unary operator expected
$ cat test
#!/bin/sh

for var in "$@"
do    
  echo $var 
  res=`curl -s -I $var | grep HTTP/1.1 | awk {'print $2'}`
    if [ $res -ne 200 ]
    then
    echo "Error on $var"
    fi
done

Upvotes: 0

Views: 1518

Answers (1)

John1024
John1024

Reputation: 113834

Consider what happens if curl does not successfully connect:

res=`curl -s -I $var | grep HTTP/1.1 | awk {'print $2'}`
if [ $res -ne 200 ]

If curl does not get any headers, or does not get a HTTP/1.1 header, then the pipline in the first command outputs nothing and res is assigned to nothing. In that case, the test in the second line will fail with an unexpected operator error.

You need to first test that res is nonempty. And, if it is empty, take an appropriate action.

Upvotes: 1

Related Questions