4

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.

4

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.

2

Check out bash_command_timer.sh by jichu4n.

https://github.com/jichu4n/bash-command-timer/

I modified my own .bashrc to include the full date.

# https://github.com/jichu4n/bash-command-timer
. bin/bash_command_timer.sh
export BCT_TIME_FORMAT='%Y-%m-%d %H:%M:%S'

Output:

$ echo 1; echo 2; echo 3
1
2
3
[ 0s031 | 2017-09-18 17:30:29 ]

Per his README:

For an explanation of how the script works, you're welcome to check out my blog post: DEBUG trap and PROMPT_COMMAND in Bash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.