0

So I have this script (nettest.sh) with the following code:

#!/bin/bash

# Internet Check

linktest="$(ping -c 1 google.com)"
if [[ $linktest != *"not"* ]]; then
  echo -e " PASSED "
  echo -e " $linktest "
else
  echo -e " FAILED "
  echo -e " $linktest "
fi

The result of the ping in case it fails is as follows:

ping: google.com: Name or service not known

But this is not working. When I have a link, It shows the right message. But when the link is down, it keeps showing the PASSED message and shows the failed ping message.

Any ideas ? (Using Debian/Kali)

Rawstring
  • 67
  • 2
  • 11

1 Answers1

2

The reason your attempt doesn't work is because ping writes to stderr when it fails, which is not captured by the $(...), and so linktest is empty.

You could make it capture stderr if you change the line to this:

linktest=$(ping -c 1 google.com 2>&1)

But actually, instead of parsing the output, it would be better to work with the exit code of ping directly, for example:

if ping -c 1 google.com; then
  echo " PASSED "
else
  echo " FAILED "
fi

You might also want to suppress all output from ping completely:

if ping -c 1 google.com &>/dev/null; then
janos
  • 120,954
  • 29
  • 226
  • 236