With "global abbreviations" in Fish 3.6.0, it's now possible to reproduce the !!
and !$
functionality of Bash (et. al.) more closely than ever. This technique has some advantages and disadvantages when compared to Bash, but if you are working on muscle-memory, I think the new methods compare very favorably. The best thing is that abbreviations are expanded in-place after the next delimiter (usually Space), so you can see (and further edit) the expansion before committing.
For !!
From the Fish doc:
function last_history_item
echo $history[1]
end
abbr -a !! --position anywhere --function last_history_item
With that in place, !!
will be expanded to the previous commandline. E.g.:
which ls
du -h $(!!)
# Automatically expands to
du -h $(which ls)
Of course, sudo !!
can be used, but I'd still encourage all Fish users to be aware of the Alt+S shortcut for prepending sudo
as mentioned in @jnns's answer -- It's far more efficient and powerful once you break yourself of the !!
muscle-memory.
That said, having !!
available for other, non-sudo
commands is great.
For !$
Probably can be improved on, but here's a first stab at a !$
implementation based on global abbreviations:
function last_history_token
echo $history[1] | read -t -a tokens
echo $tokens[-1]
end
abbr -a !\$ --position anywhere --function last_history_token
cat ~/.config/fish/config.fish
less !$
# Automatically expands to:
less ~/.config/fish/config.fish
Note that, at least currently, you do need to add a Space after the !$
in order to force the expansion. This is due to Fish attempting to parse the $
as the beginning of a variable name.
As with the sudo
/Alt+S method mentioned above, I really feel that it's just as easy to recall the last token using Alt+.. This method also works in Bash and other shells, so retraining muscle memory to prefer it over !$
is not unique to Fish.
sudo
(see [@jnns's answer])(superuser.com/a/1610597/1210833) is worth the "relearning" effort.