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.


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;)
  • 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

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.