Reputation: 70
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
Upvotes: 0
Views: 3391
Reputation: 881113
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" = "" ]
Upvotes: 2
Reputation: 84521
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.
Upvotes: 2