Bash refer to previous arguments in same line

bash, shortcut, zsh

Solution

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`:

- Works both in interactive shells and in scripts.

- Works at the individual command level, not at the line level.

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`):

- By default they work only in interactive shells, but that can be changed with `set -o history` and `set -o histexpand` (thanks, @chepner)).

- Work at the line level (more accurately: everything that was submitted with one `Enter` keystroke, no matter how many individual commands or lines it comprised).

Problem

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

Original source

Related problems