Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
most recent history line:   483  echo foo && echo 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 '14 at 20:00
See this – Stéphane Chazelas Apr 17 '14 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 '14 at 20:36
up vote 2 down vote accepted

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

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

Your Answer


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.