Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash refer to previous arguments in same line

Tags:

bash

zsh

shortcut

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.

like image 805
Ryan Kennedy Avatar asked Jan 29 '14 16:01

Ryan Kennedy


3 Answers

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).
like image 171
mklement0 Avatar answered Oct 06 '22 15:10

mklement0


!# 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.

like image 7
chepner Avatar answered Oct 06 '22 17:10

chepner


What about this:

mkdir foo; cd $_

Works for me.

like image 1
Marlon Avatar answered Oct 06 '22 17:10

Marlon