1

I'm running a script on my machine that produces a lot of output as it runs. I redirect that output to /dev/null because I'm not interested in its contents, and I capture any errors in a file (since I only care if the script fails). However, the errors in the file do not include a timestamp.

Is there a way to append a timestamp to the stderr redirect? This is the command I have, but can't figure out how to add the timestamp:

myScript.sh 2>> logfile.txt 1>/dev/null

I can't modify myScript.sh to print a date so that's not an option either. I tried something like this:

myScript.sh 2>> logfile.txt << date

but that doesn't work.

Z0OM
  • 3,149

3 Answers3

3

ts from moreutils can be used to add timestamps to each line of some output:

myScript.sh 2>&1 > /dev/null | ts >> logfile.txt

You can specify the timestamp format in a strftime()-like format:

$ seq 4 | ts '%FT%.T%z:'
2023-06-06T14:11:15.244613+0100: 1
2023-06-06T14:11:15.244693+0100: 2
2023-06-06T14:11:15.244729+0100: 3
2023-06-06T14:11:15.244759+0100: 4

For instance for a ISO8601 timestamp format with microsecond precision.

1

I also recommend ts. And an output process substitution would fit here:

myScript.sh 2> >(ts >> logfile.txt) 1>/dev/null
# ............^ yes that space is required.
glenn jackman
  • 85,964
0

You can call print the date before the script execution, like this:

echo "$(date >> logfile.txt; ./myscript.sh 2>> logfile.txt 1>/dev/null)

JCL
  • 1