Skip to content

Instantly share code, notes, and snippets.

@jstine35
Last active February 7, 2024 15:30
Show Gist options
  • Save jstine35/e0fc0e06ec06d74bc3ebd67585bf2a1d to your computer and use it in GitHub Desktop.
Save jstine35/e0fc0e06ec06d74bc3ebd67585bf2a1d to your computer and use it in GitHub Desktop.
# FIRST VERSION - Outputs UTS formatted timestamp.
# -------------------------------------------------------------------------------------
# handy pipe redirect that appends a datestamp to every line of output. Just paste this into
# the top of a typical BASH script.
s_datestamp() {
while read -r line; do
timestamp=$(date -u '+%Y-%m-%d %H:%M:%S')
# by nature BASH might run process subst twice when using >&2 pipes. This is a lazy
# way to avoid dumping two timestamps on the same line:
if [[ "$line" != \[${timestamp%% *}* ]]; then
echo "[$timestamp] $line"
else
echo "$line"
fi
done
}
exec 1> >(s_datestamp)
exec 2> >(s_datestamp)
# -------------------------------------------------------------------------------------
# SECOND VERSION - Outputs time since the script started.
# -------------------------------------------------------------------------------------
# handy pipe redirect that appends a datestamp to every line of output. Just paste this into
# the top of a typical BASH script.
procstarttime=$(date -u '+%s')
s_timestamp() {
while read -r line; do
curtime=$(date -u '+%s')
deltatime=$(( curtime - procstarttime ))
timestamp="$(printf "%03d:%02d" $(( deltatime / 60 )) $(( deltatime % 60 )))"
# by nature BASH might run process subst twice when using >&2 pipes. This is a lazy
# way to avoid dumping two timestamps on the same line:
if [[ "$line" != \[${timestamp%% *}* ]]; then
echo "[$timestamp] $line"
else
echo "$line"
fi
done
}
exec 1> >(s_timestamp)
exec 2> >(s_timestamp)
# -------------------------------------------------------------------------------------
@gergelybosze
Copy link

gergelybosze commented Jul 27, 2022

Hi, for line 9, the timestamp has a shorter option for iso with seconds:
date -Is

@kylefuhrmanncalm
Copy link

Also recommend using while IFS= read -r line so that prepended whitespace isn't removed.

@vladdevops
Copy link

Hi
(echo 1 && sleep 3 && echo 2) | while IFS= read -r line; do echo "[$(date -Is)] $line"; done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment