如何 !!在bash工作?


34

当您忘记命令开头的sudo时,此功能非常有用,!!就像上一个命令的别名一样。范例:

$ mv /very/long/path/for/a/protected/sensible/file/caution.h .
(...) Permission denined
$ sudo !!
sudo mv /very/long/path/for(...) .
[sudo] password :
  • 我们怎么称呼这个双重!!把戏?因此,通过互联网进行研究非常困难。
  • 它是如何工作的 ?我怀疑与history命令的链接。
  • 它在哪里定义?我可以自己定义其他人吗?

编辑:一些有趣的事件指示符

!!:*

它引用上一个命令的参数。用例:

cat /a/file/to/read/with/long/path
nano !!:*

:p

仅打印命令而不执行它,您必须将其放在事件指示符的末尾。

$ !-5:p
sudo rm /etc/fstab -f

这里更多


3
阅读man history
Costas

1
这是历史扩展的一种特殊情况,在这种情况下,shell尝试!在当前shell的历史列表中将单词扩展为匹配的命令。!!是一种特殊情况,等效于!-1,其中n后面的负数表示!前n个命令。
chepner

1
@Costas,更有用的方法是,阅读LESS='+/^HISTORY EXPANSION' man bash
通配符

Answers:


34

!!bash手册的“事件指示符”标题下列出:

   An event designator is a reference to a command line  entry  in  the
   history list.  Unless the reference is absolute, events are relative
   to the current position in the history list.

   !      Start a history  substitution,  except  when  followed  by  a
          blank,  newline,  carriage  return,  = or ( (when the extglob
          shell option is enabled using the shopt builtin).
   !n     Refer to command line n.
   !-n    Refer to the current command minus n.
   !!     Refer to the previous command.  This is a synonym for  `!-1'.
   !string
          Refer  to the most recent command preceding the current posi-
          tion in the history list starting with string.
   !?string[?]
          Refer to the most recent command preceding the current  posi-
          tion  in  the history list containing string.  The trailing ?
          may be omitted if string is followed immediately  by  a  new-
          line.
   ^string1^string2^
          Quick  substitution.   Repeat the previous command, replacing
          string1       with       string2.        Equivalent        to
          ``!!:s/string1/string2/'' (see Modifiers below).
   !#     The entire command line typed so far.

因此!!将被以前的命令替换。

请注意,shell历史记录将不包含文字!!,而是包含已执行的实际命令:

$ ls
[some output]

$ !! .
[same output]

$ history 3
  645  2016-08-25 17:40:55 ls
  646  2016-08-25 17:40:57 ls .
  647  2016-08-25 17:41:00 history 3
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.