0

This works:

if ! ping -q -c 1 -W 1 google.com > /dev/null; then
   echo "google not reachable"
fi

but this does not work:

if [ ! `ping -q -c 1 -W 1 google.com > /dev/null` ]; then
    echo "google not reachable"
fi

Why does the second statement not work? Is it not basically the same?

TatzyXY
  • 505
  • 1
  • 6
  • 13
  • 1
    "Square brackets" are not bash syntax. `[` is another name for the command `test`. If you couldn't run ```if test ! `ping ...` ```, you can't run ```if [ ! `ping ...` ]```. – Charles Duffy Jul 27 '19 at 21:00
  • 1
    Moreover, `> /dev/null` throws away the stdout of your command substitution's body, so there's no text for `[` to evaluate for emptiness/nonemptiness. (Not that it would work reliably without quotes regardless). – Charles Duffy Jul 27 '19 at 21:02
  • 1
    ```[ "`some command here`" ]``` tests whether `some command here` writes anything to stdout, because when you pass `test` only one argument, it checks whether that argument is empty. If you leave out the double quotes, by contrast, its behavior becomes effectively undefined, because the stdout of `some comand here` is subject to string splitting and glob expansion before `test` gets it.. – Charles Duffy Jul 27 '19 at 21:03
  • (even though bash has a built-in version of `[` for performance reasons, your operating system probably provides a `/bin/[` or `/usr/bin/[` that works exactly the same way, and which is probably a hardlink to the same executable as `/bin/test` or `/usr/bin/test`). – Charles Duffy Jul 27 '19 at 21:06
  • 1
    Without double-quotes around the backticked command, its output will be split into "words" and any words that contain wildcards will be expanded into a list of matching filenames; the result of this is passed to the `[` (`test`) command, which will attempt to treat it as some sort of expression. If the command prints something like "`a = a`", it makes sense as an expression, and `test` will evaluate that. If it prints something like "`PING google.com (216.58.193.78):`...", it's not going to make sense, and `[` will print an error. But since you redirected output, there won't be anything there. – Gordon Davisson Jul 27 '19 at 21:48

0 Answers0