I am trying to create a bash function so that I can call on it from various parts of my code.
#!/bin/bash
host='10.9.8.14'
if [ -z $host ]; then
echo "Usage: `basename $0` [HOST]"
exit 1
fi
ping_func () {
results=`ping -W 1 -c 1 $host | grep 'bytes from '`
return results
}
while :; do
result=ping_func
# result=`ping -W 1 -c 1 $host | grep 'bytes from '`
if [ $? -gt 0 ]; then
echo -e "`date +'%Y/%m/%d %H:%M:%S'` - host $host is \033[0;31mdown\033[0m"
for i in `seq 1 10`;
do
echo $i
done
if [ $i -eq 10 ]; then
service openvpn restart > /dev/null 2>&1
sleep 5
fi
else
echo -e "`date +'%Y/%m/%d %H:%M:%S'` - host $host is \033[0;32mok\033[0m -`echo $result | cut -d ':' -f 2`"
sleep 1 # avoid ping rain
fi
done
But when i call the function ping_func from within the loop, my output is as follows:
2019/06/29 08:15:38 - host 10.9.8.14 is ok -
2019/06/29 08:15:40 - host 10.9.8.14 is ok -
2019/06/29 08:15:42 - host 10.9.8.14 is ok -
2019/06/29 08:15:44 - host 10.9.8.14 is ok -
2019/06/29 08:15:46 - host 10.9.8.14 is ok -
2019/06/29 08:15:48 - host 10.9.8.14 is ok -
2019/06/29 08:15:50 - host 10.9.8.14 is ok -
Without the function, but calling ping every loop cycle, I get the correct output.
2019/06/29 08:15:26 - host 10.9.8.14 is ok - icmp_seq=1 ttl=64 time=414 ms
2019/06/29 08:15:27 - host 10.9.8.14 is ok - icmp_seq=1 ttl=64 time=407 ms
2019/06/29 08:15:29 - host 10.9.8.14 is ok - icmp_seq=1 ttl=64 time=410 ms
2019/06/29 08:15:30 - host 10.9.8.14 is ok - icmp_seq=1 ttl=64 time=412 ms
2019/06/29 08:15:31 - host 10.9.8.14 is ok - icmp_seq=1 ttl=64 time=358 ms
2019/06/29 08:15:33 - host 10.9.8.14 is ok - icmp_seq=1 ttl=64 time=466 ms
2019/06/29 08:15:34 - host 10.9.8.14 is ok - icmp_seq=1 ttl=64 time=407 ms
How do I call on my bash function and return all the string data output?
Lines of code in question:
result=ping_func
result=`ping -W 1 -c 1 $host | grep 'bytes from '`