Search code examples
variablesshraspbian

Set a variable to the output of a command in a bsh script


Running a system with UTC time I'd like to be able to write out to log files with local time so reading them later and identifying the influence of external factors for issues needs less brain work.

The command to get the local date (e.g. Sydney, Australia) when running on UTC is

TZ=Australia/Sydney date

This would return

Sat 15 Sep 17:19:28 AEST 2018

A sample of my script is below. For now, please ignore the fact it is not the best script for the job it appears to be trying to do. My issue is the time being recorded in the log file. What this script does each loop is write the same date/time into the log file - the local time when the script was started.

#!/bin/sh
localdatetime=$(TZ=Australia/Sydney date)

while
  do
    nc -zw5 192.168.0.199     # IP of router
    if [[ $? -eq 0 ]]; then
      status="up"
    else
      status="down"
    fi
  echo "$localdatetime The router is now $status" >> /home/pi/userX/routerStatus.log
  sleep 10
done

What I want is for the current local time to be stored into the log file each loop so that I know from reading the log file when the router was up or down. Is there a way to do this using a variable?

Thanks in advance for any good advice.


Solution

  • What I did in the end was the obvious solution: update the local time variable immediately before trying to write it to the log file.

    For example:

    #!/bin/sh
    
    while
      do
        nc -zw5 192.168.0.199     # IP of router
        if [[ $? -eq 0 ]]; then
          status="up"
        else
          status="down"
        fi
      localdatetime=$(TZ=Australia/Sydney date)
      echo "$localdatetime The router is now $status" >> /home/pi/userX/routerStatus.log
      sleep 10
    done