xster
Published in

xster

Get output of last command on fish shell

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

--

--

--

Collection of tech tips and learnings

Recommended from Medium

Swift — Filtering: A Real Example

Amos Crack Version

Amos

My experience with JavaFX to write Desktop Applications

Why Program? Why Python?

Using Badges — Flutter

The Proper Use of Pointers in Go (golang)

Java Lessons Learned from KBB Simulation Project

Setting up a Selenium Pipeline In Azure DevOps

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
xster

xster

More from Medium

How to use `raspi-gpio` instead of `gpio` of Wriring Pi

Meet The Newest Member of the xLeapp Family

Safer WIFI setup for Home — Small Office

Walk into the Pi World