是否可以使用 bash bang (!) 和历史记录来替换/更改参数

Sha*_*sai 4 bash command-history

我目前对 Linux 中的和based功能着迷history!bash

我已经习惯使用!!!:<argc>类似的功能,但是是否有某种方式,例如,如果我之前添加了错误的参数而犯了错误,那么我可以删除该错误的参数并再次使用命令行。

例子

如果我犯了如下错误:

      mv -r movableFolder/ targetFolder/
Run Code Online (Sandbox Code Playgroud)

由于没有-r选项mv,我想使用一些!技巧来删除它:

      mv movableFolder/ targetFolder/
Run Code Online (Sandbox Code Playgroud)

我知道我可以从上面的历史命令中执行以下操作:

     mv !:2 !:3
Run Code Online (Sandbox Code Playgroud)

但有什么办法可以mv!命令来代替吗?

小智 5

那么,您可以简化参数 2 和 3 的使用,如下例所示:

$ echo -r movableFolder/ targetFolder/
-r movableFolder/ targetFolder/

$ echo !:2*
movableFolder/ targetFolder/
Run Code Online (Sandbox Code Playgroud)

一切都记录在 man bash 中:

字指示符 字指示符用于从事件中选择所需的字。A :将事件规范与字指示符分开。如果单词指示符以 ^、$、*、- 或 % 开头,则可以省略。单词从行首开始编号,第一个单词用 0(零)表示。单词将插入到当前行中,并用单个空格分隔。

  0 (zero)  The zeroth word.  For the shell, this is the command word.
  n         The nth word.
  ^         The first argument. That is, word 1.
  $         The last word. This is usually the last argument, but will
            expand to the zeroth word if there is only one word in the line.
  %         The word matched by the most recent `?string?' search.
  x-y       A range of words; `-y' abbreviates `0-y'.
  *         All  of the words but the zeroth. This is a synonym for `1-$'.
            It is not an error to use * if there is just one word in the event;
            the empty string is returned in that case.
  x*        Abbreviates x-$.
  x-        Abbreviates x-$ like x*, but omits the last word.
Run Code Online (Sandbox Code Playgroud)

如果提供的字指示符没有指定事件,则前一个命令将用作事件。

因此,使用此行后:

$ echo -r movableFolder/ targetFolder/
echo -r movableFolder/ targetFolder/
Run Code Online (Sandbox Code Playgroud)

这会起作用:

$ !:0 !:2*
movableFolder/ targetFolder/
Run Code Online (Sandbox Code Playgroud)

还有这个:

$ !:0 !:2-$
movableFolder/ targetFolder/
Run Code Online (Sandbox Code Playgroud)