Scenario
Consider you ran ls
or git status
or foo | rg bar
and want to take one line of the output and either run something else with it or copy it to clipboard.
Solution
Fish shell is an excellent, extensible shell. It doesn’t have an easy way to re-run the last command. But it has excellent readable scripting support to create a similar effect.
We can accomplish this by using a combination of the commandline
built-in command (which manipulates the current prompt’s command buffer) and the bind
keybinding mechanism.
Create a function such as
function __select_from_last
set -l FZF_OUT (eval $history[1] | fzf --height 15%)
if test -n "$FZF_OUT"
commandline -r $FZF_OUT
commandline --cursor 0
end
end
in your functions folder in $HOME/.config/fish/functions/__select_from_last.fish
.
In the above, $history[1]
brings up the last command you ran and run it again via eval
. Pipe it through fzf
which is an excellent tool to interactively select (or fuzzy search) one line in the output of the last command. See screenshot below.
Once you select a line, the line is saved in a variable FZF_OUT
. Then commandline
is used first with -r
to replace the current command buffer with the line from the last command you selected. Then via --cursor
, move the cursor back to the beginning of the line so you can prepend another command to the line you selected.
You can then bind it with a hotkey to run the whole thing with a shortcut each time. Such as with bind \er __select_from_last
which runs the script each time you press alt-r.
In the above screenshot, after running git branch
, you can then easily press alt-r, select one line from the git branch
output and either run something else with one branch, such as git checkout
or use ctrl-x to copy it to clipboard (if the fish_clipboard_copy
function is bound to your ctrl-x).