[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: whats wrong with my internet connection checker script?



S Mathias wrote:
> $ true && true || echo hi

Both true commands invoked.  This satisfied the left hand side of the
or and so echo was not invoked.

> $ true && false || echo hi
> hi

Both true and false invoked, and then the echo.

> $ false && true || echo hi
> hi

Only the first false invoked, and then the echo.

> $ false && false || echo hi
> hi

Only the first false invoked, and then the echo.

> $ ping -W 1 -c 4 google.com >& /dev/null | grep -q "100% packet loss" && ping -W 1 -c 4 www.yahoo.com >& /dev/null | grep -q "100% packet loss" || echo "no internet connection"
> no internet connection

Only the first ping|grep invoked.  This returned false.  The grep did
not match and therefore did not return success.  The grep returned a
failure that it did not match.  I think that is not what you expected.
Since the network connection was up and online the grep 100% failed
and returned false.

This is exactly the same as you had tested above:

> $ false && false || echo hi
> hi

Exactly the same and so exactly the same result.

> $ ping -W 1 -c 4 google.com >& /dev/null | grep "100% packet loss"

  $ echo $?
  1

> $ ping -W 1 -c 4 www.yahoo.com >& /dev/null | grep "100% packet loss"
> $

  $ echo $?
  1

> ...both sides "false", because they have no output, because google.com and www.yahoo.com is reachable.
> how come it writes "no internet connection"? [at the longest line]

The first test is false and so the OR side with the echo is invoked.

Note that the second ping|grep is not invoked.  Only the first one.
Being false the OR side is invoked next.

> i just want a "oneliner" that checks if theres "internet connection" or no. :\

You would need to invert the grep exit code.  But not using grep as
you found in your later post is a better solution.

> where did I screw up? 8)

You used ">& /dev/null" to redirect both stdout and stderr to
/dev/null.  This means that there isn't any input to grep and
therefore grep can never succeed with a match.

Side Note: You are using ">& word" which is not typical.  The manual
states that using "&> word" is preferred over ">& word".  I believe
this to reduce confusion over the "2>&1" syntax.  When in doubt follow
the documentation.

Personally I never use that bash specific syntax and stick with the
standard ">/dev/null 2>&1" syntax.  And if the standard syntax had
been used in this case I think it would have made the issue obvious at
a glance.

Bob

Attachment: signature.asc
Description: Digital signature


Reply to: