Super User is a question and answer site for computer enthusiasts and power users. 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

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:

$ ls
COMMAND: ls --color
[output of ls]


$ (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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .