Bash – Echo each shell script command with a timestamp

bashshellshell-scripting

set -x or set -v prints every executed command.

How do I get the command printed with the time when the command started executing?

Best Answer

in Bash, execution of code after each command can be achieved using the "trap" builtin and the "DEBUG" level.

in bash do: help trap or refer to bash manual page, and look for the trap section

example:

trap 'date' DEBUG

This will execute the command "date" juste after each command.

Of course you can format the timestamp as you want, refer to the "date" manual page.

If you want to remove the newline, so that timestamp appears in front of next command, you can do:

trap 'echo -n $(date)' DEBUG

And to terminate this:

trap '' DEBUG

You can combine with "set -x" / "set +x"