当使用
grep
等工具或某些 git
输出(例如 status
)时,我经常想用列表中返回的(最后一个)文件进行一些操作,例如将其复制到剪贴板或查看它.
我想使用一个脚本来自动执行该操作,该脚本将重新运行最后一个命令,并识别最后返回的文件名,例如脚本:
#!/usr/bin/env bash
# Retrieve the last command from the shell history.
last_command=$(history | tail -n 1)
# Check if the last command is empty.
if [ -z "$last_command" ]; then
printf >&2 "No command found in the shell history.\n"
exit 2
fi
# Run the last command and capture its output.
command_output=$($last_command)
# Extract the last line (assuming it's a list of files).
last_file=$(printf "%s" "$command_output" | tail -n 1)
# Debugging information.
printf "Last file: %s\n" "$last_file"
尽管如此,无论出于什么原因,我无法理解,当从命令行交互运行时,
history
确实返回最后一个命令,但从脚本运行时则不会。因此 last_command
始终为空...
与
set -x
:
++ history
++ tail -n 1
+ last_command=
+ [[ -z '' ]]
+ printf 'No command found in the shell history.\n'
No command found in the shell history.
+ exit 2
有什么想法吗?
(PS-我也尝试了许多不同的替代方案,例如使用
fc
,但没有取得更多成功。)
编辑 -- 将第一个命令更改为:
history_file="$HOME/.bash_history"
last_command=$(tail -n 1 "$history_file")
向我显示了另一个最后命令,而不是
history
!?? 输出的真正最后命令
如手册页所示,您必须
set -o history
才能使历史记录可用于脚本;但即便如此,该功能的启用与您当前的交互历史记录无关。由于这看起来完全是为了交互式使用,因此您可能应该将其制作成 .bash_profile
或类似函数中的函数。
rerun () {
local last_command=$(history 2)
# Check if the last command is empty.
if [ -z "$last_command" ]; then
echo "rerun: No command found in the shell history" >&2
return 2
fi
$last_command | tail -n 1
}