Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Suppose I set a trap on DEBUG like so:

unset PROMPT_COMMAND # don't want $PROMPT_COMMAND triggering DEBUG trap
trap 'printf %s\\n "most recent history line: $(history 1)" >&2' DEBUG

If I do a simple command, then it prints my command to stderr:

$ echo foo
most recent history line:   483  echo foo

However, if I run an and/or list, the DEBUG trap is invoked multiple times, once per list command executed:

$ echo foo && echo bar
most recent history line:   483  echo foo && echo bar
foo
most recent history line:   483  echo foo && echo bar
bar

Is there a way I can get the DEBUG trap to execute only once per command (simple or otherwise) entered at the prompt? If not, what is the best way for my trap code to detect whether it has already executed since the last time the prompt was drawn?

share|improve this question
    
Sounds like you want the equivalent of zsh's preexec() hook. –  Stéphane Chazelas Apr 17 at 20:00
    
See this –  Stéphane Chazelas Apr 17 at 20:23
    
@StephaneChazelas: Thanks for the link. It looks like preexec.bash basically does what I do in my answer (via the preexec_interactive_mode variable), so maybe the approach in my answer is as non-kludgy as it can get. I do wish bash had something like zsh's preexec() hook. –  Richard Hansen Apr 17 at 20:36

1 Answer 1

The following works, but feels a bit kludgy (I'm hoping for a more clever answer):

PROMPT_COMMAND='at_prompt=t'
trap '
    [ -z "${at_prompt+set}" ] ||
    printf %s\\n "most recent history line: $(history 1)" >&2
    unset at_prompt
' DEBUG
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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