Bash历史扩展在脚本中不工作,即使使用set -H



我想在脚本中使用!!和其他Bash历史扩展特性。据我所知,set -H应该允许这样做。然而,它似乎无法扩展历史。像!!!-1这样的项目仍然不起作用。

下面是一个脚本:

#!/bin/bash
set -H
# These don't make it work either
set +f
shopt -s extglob
shopt histexpand  # This option does not exist
echo $-  # Settings are hBH
# These print literal '!' text, not history-expanded text
echo !-1
echo !!

对于非交互式shell,还必须特别启用命令历史记录:

set -o history
set -o histexpand

来源:脚本中的历史扩展