如何 !!在 bash 工作?

Tot*_*tem 35 bash command-history shell-script

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

$ mv /very/long/path/for/a/protected/sensible/file/caution.h .
(...) Permission denined
$ sudo !!
sudo mv /very/long/path/for(...) .
[sudo] password :
Run Code Online (Sandbox Code Playgroud)
  • 我们怎么称呼这种双重!!伎俩?由于该令牌,互联网上的研究很困难。
  • 它是如何工作的 ?我怀疑与历史命令的链接。
  • 它在哪里定义?我可以自己定义一些其他的吗?

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

!!:*

它指的是前一个命令的参数。用例:

cat /a/file/to/read/with/long/path
nano !!:*
Run Code Online (Sandbox Code Playgroud)

:p

只打印命令而不执行它,你必须把它放在事件指示符的末尾。

$ !-5:p
sudo rm /etc/fstab -f
Run Code Online (Sandbox Code Playgroud)

更多在这里

Kus*_*nda 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.
Run Code Online (Sandbox Code Playgroud)

so!!将替换为之前的命令。

请注意,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
Run Code Online (Sandbox Code Playgroud)