2

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.

1 Answer 1

4

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;)
$ 
1
  • 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, 2013 at 15:56

You must log in to answer this question.

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