0

I'm new to scripting.

I downloaded cygwin and Notepad++(I'm using unix option-for writing and saving the ".sh files") I have below script

Below code is from command $ cat -v pinging.sh

#!/bin/bash

target=$1
# email report when
SUBJECT="Ping failed"
EMAILID="someemailid@gmail.com"

count=$( $SYSTEMROOT/system32/ping -n -c 1 $target | grep 'received')
if [ $count == 0 ];
then
    echo "Host : $target  is not Alive!! Try again later.. at $(date)" | mail -s "$SUBJECT" $EMAILID

else
    echo "Yes! Host is Alive!"

fi
done

But my script is giving error -

$ ./pinging.sh www.google.com
./pinging.sh: line 9: [: ==: unary operator expected
Yes! Host is Alive!
./pinging.sh: line 17: syntax error near unexpected token `done'
./pinging.sh: line 17: `done'

I'm not sure what I am doing wrong here.

  1. The script is giving error
  2. I'm getting- "host is alive" message always even in case of destination unreachable messages too. If I'm using ping www.somesite.com and if I'm getting destination unreachable through cygwin or cmd, this code is giving host is alive.

    I also tried if [ $count -et 0 ]; in above code

Please help me!

Best Regards,

1 Answers1

1

The value of the $count variable is not a number. It is a full line of text.

When you expand it in the [ test (without quotes) it gets word-split by the shell and the contents of the [ test become invalid (too many words) and you get your error.

If you quote "$count" you will avoid the error (but still not get the results you want).

You need to filter out only the number from the ping output and then use that in your [ test.

Add set -x to the top of your script to see the commands that are actually being run and you'll see the problem.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148