使用最后一条命令的参数运行命令


34

运行命令时,有时可能需要使用最后一条命令中的参数来运行命令。你该怎么做?

当然,除了使用方向键和Del键:... DelDelDel... Del<new_command>

Answers:


45

例如,如果您运行以下命令:

mkdir long_path_here/new_dir

您最有可能想进入最近创建的目录。您可以使用下一个“快捷方式”执行此操作:

  • cd Esc.-键入cd,然后按,Esc然后按.(不同时)。如果先前的命令没有参数,则您将获得先前的命令本身。
  • cd !*-在这种情况下,您将从previuos命令获取所有参数。如果前面的命令没有参数,您将一无所获。
  • cd Alt+ .-键入cd,然后按Alt.(同时)。实际上,使用这种方式并继续按下.(不释放Alt),您将获得历史记录中每个命令的最后一个参数。如果命令没有参数,您将获得命令本身。

通常:<command> Esc.<command> !*<command> Alt+ .


哇,您救了我数百个小时,而我可能会在接下来的几年里浪费

32

如果您要使用上一个命令的所有参数,或者只想使用最后一个参数,则有一些快捷方式。

  • 对于所有参数: <command> !*
  • 对于最后一个参数: <command> !$

例子:

ls foo/ bar/
ls !* # Gives the results of ls foo/ bar/

ls foo/ bar/
ls !$ # Gives the results of ls bar/

如果要从上一个命令的参数列表中选择一个参数,则可以使用 <command> !!:<argNumber>

例:

ls foo/ bar/ baz/
ls !!:2 # Gives the results of ls bar/
ls foo/ bar/ baz/
ls !!:1 # Gives the results of ls foo/

2
您只需要一个!arg版本中的一个,例如!:2。假设默认bash。
belacqua 2013年

3
您也可以!^代替使用!:1
帕迪·兰道

7

提到!*,这!$是一件好事,但是当您需要做一些编辑时,readline快捷方式将为您提供帮助!

例如,而不是无数... DelDelDel... Del你可以只按 Ctrl-a(跳转到该行的开始) Alt+d(删除到单词的末尾)

有关更多信息man readline,请搜索Default key bindings


4

要从n上一个命令中获取th参数,请输入Alt+ n+ Alt_。例如,之后:

$ echo 1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

键入,echo然后Alt2Alt_在下一个提示符下输入:

$ echo 2

点击后的“屏幕截图” Alt2是:

(arg: 2) echo

您可以重复Alt_多次以n连续获取先前命令的th参数。

另一个有用的想法是定义别名r="fc -s"。然后,您可以执行命令替换:

$ echo 1
1
$ r echo=history
history 1
27755  history 1
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.