How to log echo statement with timestamp in shell script

11,426

Solution 1

Depending on the exact intended behavior you may want the ts utility.

% echo message | ts
Apr 16 10:56:39 message

You could also alias echo.

% sh
$ alias echo='echo $(date)'
$ echo message
Mon Apr 16 10:57:55 UTC 2018 message

Or make it a shell function.

#!/bin/sh

echo() {
    command echo $(date) "$@"
}

echo message

Solution 2

Here I'm using a function to simplify the line, but the main thing to look for is process substitution, that's the >(log_it) syntax. REPLY is the default variable used by read.

logit() {
    while read
    do
        echo "$(date) $REPLY" >> ${LOG_FILE}
    done
}

LOG_FILE="./logfile"

exec 3>&1 1>> >(logit) 2>&1

echo "Hello world"
ls -l does_not_exist

The example puts into logfile:

Mon 16 Apr 2018 09:18:33 BST Hello world
Mon 16 Apr 2018 09:18:33 BST ls: does_not_exist: No such file or directory

You might wish to change the bare $(date) to use a better format. If you are running bash 4.2 or later you can use printf instead, which will be more efficient, for example, instead of the echo:

# -1 means "current time"
printf "%(%Y-%m-%d %T)T %s\n" -1 "$REPLY"  >> ${LOG_FILE}

Gives:

2018-04-16 09:26:50 Hello world
2018-04-16 09:26:50 ls: does_not_exist: No such file or directory
Share:
11,426
Galet
Author by

Galet

Updated on June 04, 2022

Comments

  • Galet
    Galet almost 2 years

    I am currently using following to log stdout and stderr. I want to log echo statements along with timestamp.

    exec 3>&1 1>>${LOG_FILE} 2>&1
    

    How can I achieve it using shell

  • Galet
    Galet almost 6 years
    I want to store it in a file. How to use it.