Alex Rivera | Logout

zsh preexec command modification

Asked 2012-09-25T10:04:14.810
10

Is there a way to modify the command that is about to execute? I would like to redirect the output to a file, as well as print it on the terminal. I found that ls > file.txt | cat does the job, so I would like to add that > file.txt | cat to any command that is about to execute.
Is there a better way to redirect to file and print to terminal? I am trying to make a logger.

Edit
Report

1 Answer

10

You can change the action that is performed when you execute a line to alter the command that will be executed. This can be done by defining a function which you then bind to the enter key.

Lets first define a function that can add the '> file.txt | cat' ending to any command:

function log_and_accept {
    BUFFER="$BUFFER > file.txt | cat"
    zle accept-line
}

The next part is to actually replace the default enter key behaviour with your new function. The default behaviour we are replacing is the accept-line function, and if we look at the zle documentation, you will see that accept-line is bound to ^J and ^M.

To bind this function to those letters you first need to turn it into a widget:

zle -N log_and_accept_widget log_and_accept

Then you can bind it, replacing the old behaviour:

bindkey '^J' log_and_accept_widget
bindkey '^M' log_and_accept_widget

Now you will be expanding that command for every single command you do. Every cd, ls, vim etc etc. As such I recommend that you define a couple more functions that actually turn this on and off:

function turn_on_logging {
    bindkey '^J' log_and_accept_widget
    bindkey '^M' log_and_accept_widget
}
function turn_off_logging {
    bindkey '^J' accept-line
    bindkey '^M' accept-line
}

zle -N turn_on_logging_widget turn_on_logging
zle -N turn_off_logging_widget turn_off_logging

bindkey '^P' turn_on_logging_widget
bindkey '^O' turn_off_logging_widget

I think you should be careful with this. After testing it a little, I quickly grew to dislike it.

answered 2013-01-31T20:22:52.270

Your Answer