0

I'm trying to create a timestamp for the information produced from the below .sh file when it is ran and the "echo"'s are performed. What is the best way to go about doing this?

echo "Target File" >> /cygdrive/c/FilePath/Log.txt
if [ -f //TargetDirectory/TargetFile ]
then
    echo //TargetDirectory/TargetFile is present. >> /cygdrive/c/FilePath/Log.txt
else
    echo //TargetDirectory/TargetFile is missing. >> /cygdrive/c/FilePath/Log.txt
fi
echo -e "\n" >> /cygdrive/c/FilePath/Log.txt
Michael
  • 5,095
  • 2
  • 13
  • 35
RozS94
  • 3
  • 1

3 Answers3

2
echo () {
    builtin echo "$(date +'[%m-%d %H:%M:%S]'):" "$@"
}

Just override echo.

Mihir Luthra
  • 6,059
  • 3
  • 14
  • 39
2

If you want to timestamp all output (to STDOUT) from your script, not just that produced by echo:

#!/bin/bash

timestamp () {
    while read -r line
    do
        echo "$(date --iso-8601=ns) $line"
    done
}

exec > >(timestamp)

echo "Target File" >> /cygdrive/c/FilePath/Log.txt
if [ -f //TargetDirectory/TargetFile ]
then
    echo //TargetDirectory/TargetFile is present. >> /cygdrive/c/FilePath/Log.txt
else
    echo //TargetDirectory/TargetFile is missing. >> /cygdrive/c/FilePath/Log.txt
fi
echo -e "\n" >> /cygdrive/c/FilePath/Log.txt
printf '%s' "something"
whoami

If you're trying to profile the execution of a script, see my answer here.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
1

I would write a log function.

function log()
{
    echo "$(date +'[%m-%d %H:%M:%S]'):" $* >> /cygdrive/c/FilePath/Log.txt
}

log "Target File"
if [ -f //TargetDirectory/TargetFile ]
then
    log //TargetDirectory/TargetFile is present.
else
    log //TargetDirectory/TargetFile is missing.
fi
log -e "\n"
ddoxey
  • 2,013
  • 1
  • 18
  • 25