Bash – How to stamp prompt at command execute time

bashprompttimestamps

How do I append a timestamp to the prompt when a command is started? I'm looking for a solution halfway between a static prompt and continuous clock.

The main difference being the static prompt will show the time when the prompt was loaded. If I let it sit for a few minutes, then enter a command, that's when I want another timestamp to be added. My goal is to be able to easily see the time difference taken to execute commands, and how long a prompt sat idle. The problem with the continuous clock answer, aside from the fact that I want to use bash, is that it would lose the start timestamp because it would refresh the whole thing.

For example, I would like my prompt to look like this when I open a new shell:

10:30:21 jeff ~ $

Then let's say it just sits there for a minute before I actually finish typing a command and hit Enter

10:30:21 jeff ~ 10:31:28 $ ./long_running.sh
10:36:52 jeff ~ $

Notice it appends another timestamp showing when I actually executed the command. And I can easily see that the command took about 5 minutes to run by subtracting from the start timestamp on the next prompt.

Best Answer

There's a DEBUG trap that can be called before every command is run

eg

trap 'echo -e "\nStarted at: $(date)\n"' DEBUG

So if I do that:

$ trap 'echo -e "\nStarted at: $(date)\n"' DEBUG
$ pwd

Started at: Thu Aug 18 11:59:33 EDT 2016

/home/sweh
$ echo hello

Started at: Thu Aug 18 11:59:35 EDT 2016

hello
$ sleep 100

Started at: Thu Aug 18 11:59:37 EDT 2016

It's not rewriting the prompt, but you can see how it can be made to output stuff before every comamnd. You can make the trap function as complicated as you need.

Related Question