Get output of last command on fish shell

xster
xster
Jan 27 · 2 min read

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.

Image for post

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).

xster

Collection of tech tips and learnings

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store