为什么 history 命令在脚本文件中什么都不做?

Sep*_*our 4 bash command-history shell-script

如果我创建一个包含

 #!/bin/bash 
 history
Run Code Online (Sandbox Code Playgroud)

并运行它,我没有输出。在终端中手动运行它或sourceing 脚本文件确实会产生输出。

为什么history不能从文件工作?

Adr*_*rth 15

第二个命令确实“有效”,但未为非交互式 shell 启用历史记录,这就是它在您的脚本中不返回任何内容的原因。

在非交互式 shell 中测试默认值:

nohistory.sh

#!/bin/bash
set -o | grep history
history
Run Code Online (Sandbox Code Playgroud)

结果:

$ ./nohistory.sh
history         off
Run Code Online (Sandbox Code Playgroud)

启用历史记录set -o history

history.sh

#!/bin/bash
set -o history
set -o | grep history
history
Run Code Online (Sandbox Code Playgroud)

结果:

$ ./history.sh
history         on
    1  set -o | grep history
    2  history
Run Code Online (Sandbox Code Playgroud)