2

I'm trying to understand what is the unix command !$.

For example, I know that the command !1 is used to run the history command number 1.

It seems like !$ runs the last command typed in the bash.

For example if I wrote mv folder12 folder123 and then I would write cd !$ I would actually preform cd folder123.

Is it correct that !$ runs the last command typed in the bash?

tux3
  • 7,171
  • 6
  • 39
  • 51
SyndicatorBBB
  • 1,757
  • 2
  • 26
  • 44

1 Answers1

5

!$ matches the last argument of the previous command.

From man bash

yank-last-arg (M-., M-_)

Insert the last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn. The history expansion facilities are used to extract the last argument, as if the "!$" history expansion had been specified.

Example

$ vi a
$ ls -l !$ # expands to "ls -l a"
-rw-rw-r-- 1 me me 30 18 abr.  22:00 a

See also What is your single most favorite command-line trick using Bash?:

I'm a fan of the !$, !^ and !* expandos, returning, from the most recent submitted command line: the last item, first non-command item, and all non-command items. To wit (Note that the shell prints out the command first).

And also a good reading: The Definitive Guide to Bash Command Line History.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • So to answer the last question, `!$` runs the last command only if it did not take any argument. – tux3 Apr 20 '15 at 19:12
  • Though M-. might be a better one to learn if you have to pick just one. It copies the last argument of the previous command for editing. – tripleee Apr 20 '15 at 19:13
  • 1
    @EricRenouf If there was a single command with no argument, it will expand to that command. Try it. – tux3 Apr 20 '15 at 19:27
  • True. If you do `ls` alone, `!$` will expand to that. – fedorqui Apr 20 '15 at 19:28