!$ 在 Bash 脚本中是什么意思?

nux*_*nux 5 command-line bash

在阅读脚本的内容时,我发现了以下内容:

echo "An Example" > !$
Run Code Online (Sandbox Code Playgroud)

所以我想知道!$bash 是什么意思。

Rad*_*anu 9

来自man bash(在 3813 行之后的某处):

!      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).

[...]

$      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.
Run Code Online (Sandbox Code Playgroud)

因此,!$它将从历史记录中的最后一个命令中调用最后一个参数。

以下是一些示例和等效项:

!      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).

[...]

$      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.
Run Code Online (Sandbox Code Playgroud)

所有这些都只能在交互式 shell内工作。但是,如果您在脚本中使用问题中的该命令,正如您所说的那样,那么事情就不同了:当您运行脚本时,这将在一个新的外壳程序中启动,一个非交互式外壳程序,因此历史在这种情况下,扩展没有任何影响,因此命令:

echo "An Example" > !$
Run Code Online (Sandbox Code Playgroud)

!$如果不存在则创建文件(否则覆盖它)并写入An Example其中。


nux*_*nux 4

好吧,我发现 !$ 意味着最后一个参数,例如:

touch /tmp/file1
Run Code Online (Sandbox Code Playgroud)

这里的参数是/tmp/file1,所以!$在 echo example 中被替换/tmp/file1

如果随后键入该命令du -b !$,输出将为磁盘使用情况(以字节为单位)/tmp/file1

  • 你的答案有一些问题: 1. **最后一个论点**来自哪里?2.答案不是真的,您按照您所说的在脚本中使用该命令(阅读[我的答案](http://askubuntu.com/a/496120/147044)直到最后理解为什么)! (2认同)