tested with:

tested with/on:
Static hostname: CentOS1.localdomain

Operating System: CentOS Linux 7 (Core)

Kernel: Linux 4.15.9

Architecture: x86-64

bash -version

GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)

ping -V
ping utility, iputils-s20160308

usage:

/scripts/count_host_uptime.sh domain.com

cat /scripts/count_host_uptime.sh domain.com


#!/bin/bash

# ping -c 1 127.0.0.1 ; echo $?
# 0
#    success:	code 0
#
# ping -c 1 192.168.1.5 ; echo $?
# 2
#    error:	code 2
#
# mystery: there might be more error codes like 68 or 2

if [ -z "$1" ] 
then
	echo "missing argument, please give ip or domain name. exit.";
	exit; 
else
	echo $1;
fi

ALIVE=0;	# if host is alive
COUNTER=0;	# counted seconds of uptime
echo $1" uptime in seconds:" > count_host_uptime.log;	# init counted seconds uptime file.log
while true;
do
	if ping -c 1 $1 &> /dev/null
	then
		echo "host "$1" alive since "$COUNTER" seconds";
		echo "ping exits with code: "$?; # host alive;
		let COUNTER=COUNTER+1;
		echo $COUNTER >> count_host_uptime.log;
	else
		EXIT_CODE=$?; # trying to preserve exit code of ping to be returned on script exit
		echo "ping exits with code: "$?; # down
		echo "host "$1" unreachable... exit";
		exit $EXIT_CODE;
	fi
	sleep 1;
done;

example output:

/scripts/count_host_uptime.sh domain.com
domain.com
host domain.com alive since 0 seconds
ping exits with code: 0
host domain.com alive since 1 seconds
ping exits with code: 0
host domain.com alive since 2 seconds
ping exits with code: 0
host domain.com alive since 3 seconds
ping exits with code: 0
^C

Links of inspiration:

https://stackoverflow.com/questions/18123211/checking-host-availability-by-using-ping-in-bash-scripts

admin