Created
August 16, 2021 21:22
-
-
Save hoehrmann/792b5db59c30365023c7e90104bdfe15 to your computer and use it in GitHub Desktop.
Bash: prefix output of all commands with timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...