Bash output of date in bash script

I wrote this script:

#!/bin/bash
target="1.1.1.1"
while true;
do
        ping $target -c 1 -v > /dev/null
        if [[ $? -ne 0 ]]; then
                echo "$(date +"%d/%m/%y %R:%S")" >> netStabilityLog
        fi
        sleep 5s
done

It works almost perfectly, there is just one problem. In the ouptut file netStabilityLog, I get:

28/06/22 17:19:26
28/06/22 17:20:06
28/06/22 17:45
28/06/22 18:36:00
28/06/22 18:51

Sometimes, the seconds are not shown. Why is that?

Asked By: Julian Zalewski

||

It appears that you may have had multiple, slightly different, copies of the script running at once, each writing to the same output file. At least one running version of the script was not adding the seconds to its output.

As for the script itself, I could possibly give my take on it, which gets rid of the external date utility and which does the conditional outputting and redirection differently. It also sorts out the missing quoting.

#!/bin/bash

ipaddr=1.1.1.1

while true; do
    if ! ping -c 1 "$ipaddr" >/dev/null 2>&1
    then
        printf '%(%d/%m/%y %T)Tn' -1
    fi
    sleep 5
done >>netStabilityLog

This uses the %(...)T formatting string with printf, introduced in bash release 4.2. The argument -1 causes printf to use the current time when creating the output timestamp. It also does not redirect for each printf call but rather once only, for the outer loop.

The code gets rid of the explicit test against $? by using ping directly with if. The ping is not called with -v (for verbose output) as we’re discarding the output anyway.

Answered By: Kusalananda
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.