0

I'm trying to make a script that continuously attempts to ping a domain until it becomes reachable. My aim is to exit with a 0 on success and a 1 on fail after all retry attempts have exceeded.

Here's the script:

#! /bin/bash

attempt_counter=0
max_attempts=20

until $(ping -c 1 "$1"); do
    if [ ${attempt_counter} -eq ${max_attempts} ];then
      echo "Max attempts reached"
      exit 1
    fi

    printf '.'
    attempt_counter=$(($attempt_counter+1))
    sleep 5
done

However, as soon as the ping is a success, the exit doesn't occur and a weird error is displayed instead:

/var/opt/openvpn/wait-on-ping.sh some.domain
ping: unknown host some.domain
.
ping: unknown host some.domain
.
######## AS THIS POINT DOMAIN IS REACHABLE ########
/var/opt/wait-on-ping.sh: line 6: PING: command not found

Is my until condition written incorrectly since my ping exits with 0 on success?

johnabrams7
  • 399
  • 2
  • 10
BlackHoleGalaxy
  • 9,160
  • 17
  • 59
  • 103
  • 3
    What's with the `$( )`? – Charles Duffy Aug 08 '18 at 17:06
  • 2
    That is to say, your code should just be `until ping -c 1 "$1"; do`, maybe with a `>/dev/null` or such if you don't want `ping`'s output going to the TTY. – Charles Duffy Aug 08 '18 at 17:07
  • 1
    ...btw, I would also suggest `if (( attempt_counter == max_attempts )); then` -- if you've got a bash shebang, might as well take advantage of it and use C-style math. Similarly, `(( ++attempt_counter ))` is a shorter increment. – Charles Duffy Aug 08 '18 at 17:08

1 Answers1

2

$(...anything...) expands to the output from the command ...anything....

Thus, if ping emits a string on its stdout that starts with the word PING, then $(ping) will try to run PING -- that output -- as a command. (By contrast, var=$(ping) would assign that output to a variable, or [ -n "$(ping)" ] would test whether that output was empty or not).


Take out the command substitution if you don't want this behavior: Your code should just be:

 until ping -c 1 "$1"

...with no $( ) involved.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441