Bash – How to Execute a Command Before Every Bash Command

bashcommand lineshell

Does anyone know a mean of putting a 'time' command before every command in a bash session?

Best Answer

Sorry for the wrong answer before, I missunderstood your question.

To have the time added before every command that you execute on the shell you can do something like this

bind 'RETURN: "\e[1~time \e[4~\n"'

This will rebind the return key. Now every time you press return instead of writing a newline \n it will go to the beginning of the line, enter the text 'time' and a space, go to the end of the line and enter the newline \n thereby producing the desired effect.

If you don't want to sacrifice your Enter Key you could make a 'second' benchmark-enter Key like F12 by binding the command like this

bind '"\e[24~": "\e[1~time \e[4~\n"'

Now instead of replacing the return key you bound F12.

The background of all this is that bash uses GNU readline to read commands. So readline would be a good starting point for further command manipulation, etc.

Related Question