Echo each shell script command with a timestamp
set -x
or set -v
prints every executed command.
How do I get the command printed with the time when the command started executing?
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"
In Bash, you can use PS4
- which is used by set -x
to prefix tracing output.
PS4='+ $(date "+%s.%N")\011 '
set -x
...
\011 is the horizontal tab character
Not saying this is a perfect solution by any means, but I think it basically accomplishes what you need. Just wrap the main script in a function and have a separate function to call the time. I'm sure this could be greatly improved upon to get the exact desired result, but here's what I came up with:
#!/bin/bash
tstamp() { date +[%T:%N]; }
yourscript() {
set -x
echo hello
sleep 1
echo this
sleep 2
echo is
sleep 3
echo an
echo example
}
yourscript | while read line; do echo -e "$(tstamp)\t$line"; done
The above script outputs the following:
+ echo hello
+ sleep 1
[16:17:33:344851100] hello
+ echo this
+ sleep 2
[16:17:34:352269700] this
+ echo is
+ sleep 3
[16:17:36:380810900] is
+ echo an
+ echo example
[16:17:39:392033300] an
[16:17:39:414361400] example