0

I'm building a simple tool that will let me know if a site "siim.ml" resolves. If I run the command "ping siim.ml | grep "Name or service not known"" in the linux command line then it only returns text if the site does not resolve. Any working site returns nothing.

Using this I want to check if the result of that command is empty, and if it is I want to perform an action.

Problem is no matter what I do the variable is empty! And it still just prints the result to stdout instead of storing it.

I've already tried switching between `command` and $(command), and removed the pipe w/ the grep, but it has not worked

#!/bin/bash

result=$(ping siim.ml | grep "Name or service not known")

echo "Result var = " $result

if ["$result" = ""]
then
        #siim.ml resolved
        #/usr/local/bin/textMe/testSite.sh "siim.ml has resolved"
        echo "It would send the text"
fi

When I run the script it prints this:

ping: siim.ml: Name or service not known
Result var =
It would send the text
1
  • if ["$result" = ""] is not right. When result is empty, that becomes if [ = ] which succeeds because = is not the empty string! Commented Jun 25, 2019 at 23:29

2 Answers 2

2

Or even slightly more terse, just check whether ping succeeds, e.g.

if ping -q -c 1 siim.ml &>/dev/null
then
    echo "It would send the text"
    ## set result or whatever else you need on success here
fi

This produces no output due to the redirection to /dev/null and succeeds only if a successful ping of siim.ml succeeds.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked for me, thanks! I think I was getting the result of the ping confused with the output.
Yes, happens. Remember, you can always use the return of the command directly as the test in an if ... then ... fi rather than trying to save the output. Good luck with your scripting.
2

It's almost certainly because that error is going to standard error rather than standard output (the latter which will be captured by $()).

You can combine standard error into the output stream as follows:

result=$(ping siim.ml 2>&1 | grep "Name or service not known")

In addition, you need spaces separating the [ and ] characters from the expression:

if [ "$result" = "" ]

2 Comments

when I make this chage the result becomes Result var = ping: siim.ml: Name or service not known ./checkSiim.sh: line 8: [ping: siim.ml: Name or service not known: command not found
So it assigns the var but then breaks line 8 which is the if statement?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.