3

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?

3

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

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.