Skip to content

Instantly share code, notes, and snippets.

@hoehrmann
Created August 16, 2021 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoehrmann/792b5db59c30365023c7e90104bdfe15 to your computer and use it in GitHub Desktop.
Save hoehrmann/792b5db59c30365023c7e90104bdfe15 to your computer and use it in GitHub Desktop.
Bash: prefix output of all commands with timestamp
function process_command() {
if [ "$$" -eq "$BASHPID" ]; then
if [[ "$HANDLER_INSTALLED" -ne "1" ]]; then
exec > >(
trap "" INT TERM;
awk '{ print strftime("%Y-%m-%d %H:%M:%S ", systime()) $0; fflush(stdout) }'
)
exec 2> >(
trap "" INT TERM;
awk '{ print strftime("%Y-%m-%d %H:%M:%S ", systime()) $0; fflush(stdout) }' >&2
)
export HANDLER_INSTALLED=1
fi
fi
}
function prompt_command() {
exec &>/dev/tty
export HANDLER_INSTALLED=0
sleep 0.3
}
PROMPT_COMMAND="prompt_command"
trap process_command DEBUG
@hoehrmann
Copy link
Author

Quick and dirty, was just wondering if this can be done. The sleep is unfortunate, but the bash prompt will otherwise occasionally appear in the middle of the command outputs. There ought to be a better way to do that, suggestions welcome.

This could be used e.g. in an ENTRYPOINT in a Docker container that runs some CI/CD jobs, but the environment does not otherwise tell you which parts of which jobs are slow...

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