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?

1 Answer 1

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]$ '
3
  • 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. Sep 11, 2012 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. Sep 11, 2012 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. Sep 12, 2012 at 15:00

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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