Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

On bash, is there any simple way to run a command every time another command is entered in your shell?

I know about 'trap ... DEBUG', but unfortunately it does not run the specified code for every command. For example:

$ trap 'echo "COMMAND: $BASH_COMMAND"' DEBUG
$ ls
COMMAND: ls --color
[output of ls]

But:

$ (for a in `seq 1 10`; do echo -n "$a "; done;)
1 2 3 4 5 6 7 8 9 10

I would like something that'd give me "COMMAND: (for a in ...)", eg, any command inserted at the prompt.

share|improve this question

1 Answer 1

You can use

PROMPT_COMMAND='printf "COMMAND:%s\n" "$(fc -ln|tail -1)"'

which prints the previous command after its output (before the next prompt)

$ PROMPT_COMMAND='printf "COMMAND:%s\n" "$(fc -ln|tail -1)"'
COMMAND:     PROMPT_COMMAND='printf "COMMAND:%s\n" "$(fc -ln|tail -1)"'
$ ls
32-but ubuntu-gnome/  IE9 - Win7/
[output of ls]
COMMAND:     ls
$ (for a in `seq 1 10`; do echo -n "$a "; done;)
1 2 3 4 5 6 7 8 9 10 COMMAND:    (for a in `seq 1 10`; do echo -n "$a "; done;)
$ 
share|improve this answer
    
this is an improvement over what I had, the only drawback I see is that this gives the wrong output when HISTCONTROL=ignoreboth is enabled, and previous command started with a space. It also requires bash history being enabled, but that goes without saying :) –  rabexc Aug 10 '13 at 15:56

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.