I seem to remember that bash
had a bang-shortcut for referring to something in the same line. I know and use !$
, !!
and friends regularly. I recall reading being able to do something like the following:
mkdir tmp && cd !_
where !_
represents the combination I can't remember. (The goal of the above is to make a directory and immediately cd
into it upon success.) Google only yields reposts of the same 2 reference tables which don't have this combination.
Right now I'm using the less-efficient
mkdir tmp
cd !$
which gets the job done but not the way I want to do it.
Does anyone know this elusive shortcut?
In case it matters, I use zsh
with oh-my-zsh
, not vanilla bash
.
mkdir tmp && cd "$_"
is what you're looking for, I believe (you can drop the double quotes if you're sure that quoting is not needed).
$_
expands differently in different contexts, but the one that matters here (from man bash
, v3.2.51):
expands to the last argument to the previous command, after expansion.
Background:
Note: the following discusses bash
, but it seems to apply to zsh
in principle as well.
$_
is a so-called special parameter, which you'll find listed among others (without the $
prefix) in the Special Parameters
section of man bash
:
By contrast, !
-prefixed tokens (such as !$
to recall the most recent line's last token) relate to the shell's [command] history expansion (section HISTORY EXPANSION
of man bash
):
set -o history
and set -o histexpand
(thanks, @chepner)).Enter
keystroke, no matter how many individual commands or lines it comprised).!#
refers to the command line so far, and you can extract specific words from it:
mkdir tmp && cd !#:1
The same syntax works in zsh
as well.
What about this:
mkdir foo; cd $_
Works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With