I created a function clip that copies the output of the last command to clipboard by rerunning it first.
#copy previous output to clipboard
function clip(){
echo $(!!) | pbcopy
}
When I run the individual line contained in the function in my terminal it works perfectly. However, if I try to save it as a function in my .zshrc and execute it by calling clip, I get the following error:
zsh: command not found: !!
I can't get the automatic expansion to work properly, any help would be appreciated.
clip () {
fc -ILe- | pbcopy
}
History expansion with !!
only works if it is typed into an interactive commandline. It will not work from within a script as !!
is not handled in a special way there (leading to the "command not found" error).
Instead you can use the fc
command to retrieve elements from the history.
Running fc
without any parameters will retrieve the last history event and open an editor with the event in it for editing. Closing the editor will then run the edited command (not saving an edit will lead to the original command to be executed).
The parameters from the above example will modify the behavior as follows:
-I
: Only retrieve internal history events, that is, exclude events loaded from $HISTFILE.-L
: Only retrieve local history events, excluding elements shared form other sessions via SHARE_HISTORY
. (This may not be necessary in combination with -I
, but I did not test this)-e ename
: use ename
as editor instead of the default editor. if ename
is set to -
, then no editor is opened.-I
and -L
are not strictly necessary, but they prevent you from inadvertently running which ever command was typed in last in some previous shell session. This could very well have been rm -r *
or poweroff
.
So in combination fc -ILe- | pbcopy
will retrieve the last command entered into the current shell session and pipe its output to pbcopy
.
BTW: You can just use cmd1 | cmd2
instead of echo $(cmd1) | cmd2
in order to be able to pipe the output of cmd1
to cmd2
.