0

I started using this answer to print the elapsed command time in my prompt. But whenever I enter fix mode, the trap command is also echoed. Here's an example:

[last: 0s][~]$ sleep 2 && echo hello world
hello world
[last: 2s][~]$ fc
sleep 2 && echo hello world
timer_start
timer_start
hello world

I found this much more complicated prompt that also uses the DEBUG trap, but doesn't suffer from this problem- it just prints the commands and the results:

...$ sleep 2 && echo hello world
hello world
...$ fc
sleep 2 && echo hello world
hello world

But I can't figure out how it accomplishes this. How can I use the first example without having timer_start echoed for each executed command?

Community
  • 1
  • 1
user1564022
  • 55
  • 1
  • 4

1 Answers1

2

set -vx shows that start_timer is called when stop_timer (PROMPT_COMMMAND)is called so it's called one too many times.

a shorter solution :

trap 'timer=$SECONDS' DEBUG
PS1='[last: $((SECONDS-timer))s][\w]$ ' 

and even shorter

trap 'SECONDS=0' DEBUG
PS1='[last: ${SECONDS}s][\w]$ ' 

another solution : use the time in prompt

trap 'date "+[%H:%M:%S]"' DEBUG
PS1='[\t][\w]$ '
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36
  • That doesn't work. I think PS1 gets assigned a single time in your example and so the prompt value is always the same: 0s. – user1564022 Sep 11 '12 at 11:03
  • It still doesn't work for me (on version 3.2.48), even though my guess at the cause was wrong. It always prints 0s. – user1564022 Sep 11 '12 at 11:23
  • I think you didn't even bother to test any of these suggestions because they don't work in the real world. The first two don't work with compound commands like the examples in the OP and the last doesn't work if you set the PROMPT_COMMAND. – user1564022 Sep 12 '12 at 15:00