My f() function in Zsh (and maybe Bash)

January 5, 2010


Familiar with the following?

You are aware of (shell)file which contains a interesting line and you think: “I want to execute this line on the command prompt”. Most people will do the following:

% more <file>
[select interesting bit with your mouse]

And the code gets executed.

I propose the following function: f(), which does the following:

  1. It opens the file in $EDITOR (:= vim of course);
  2. You delete everything you don’t want to execute;
  3. What’s left gets executed;
  4. And it is added to your shell’s history.

The code of the function looks like this:


edit a file, exec what’s left when

you are finished editing

add what is executed to the history (fc -R)

f() { if [[ ! -f $1 ]]; then return 1; fi

copy=$(mktemp ${TMPPREFIX:-/tmp/shell}.XXXXXXX)
if cp $1 $copy; then
if ${EDTIOR:-vi} $copy; then
    $SHELL $copy
    # add to hist
    fc -R $copy
    rm -f $copy

else return 1 fi } }CODE

It should either be possible to use this verbatim in bash or make it work with a few tweaks.