Bash script to run command when remote server is available

时间:2018-11-13 14:20:56

标签: bash

I have an application which depends on another remote service. What's I'd like to do is to make simple script which will run command locally when remote server will be available.

Something like this:

#!/bin/bash 

CONNECTED = 0

while [ $CONNECTED != 1 ]; do
    if [ $(ping my-service.com) != null ] then
        my-command.sh
        let CONNECTED = 1
    fi

    sleep 2
done

Actually it doesn't work because of ping command. It cause 'Name or service not known' error. I can compare string fully to make it work, but the question is if there are any ready-to-use commands, libs to do the same? Or mb this approach is bad and I should do it in another way.

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

#!/bin/bash 

CONNECTED=1

while [[ $CONNECTED != 0 ]]; do
    ping -c1 my-service.com 
    CONNECTED=$?
    if [[ $CONNECTED == 0 ]] ; then
        my-command.sh
    fi
    sleep 2
done

$?包含最后执行的命令的返回值(在这种情况下为ping)。当ping返回0时,表示没有错误,因此它将执行my-command.sh

答案 1 :(得分:0)

最后我来了。如果有人需要,我会把它放在这里

#!/bin/bash 

until nc -z -v -w60 my-service.com 80
do
  echo "Waiting for connection..."
  sleep 2
done

command.sh