首页 > 解决方案 > 用于检测终端中运行的最后一个命令的 Bash 脚本

问题描述

我必须制作一个脚本来打印用户使用的所有命令。因此,我尝试制作一个将在后台运行并删除历史记录并注册从那一刻起运行的每个命令并将其回显到文件中的脚本。这是我做的,但不工作。

function add_new_command() {
    nr=$(history | wc -l)
    
    if [ $nr -eq 1 ]; then 
        comanda=$(history | head -n 1)
        echo $comanda > mycommands
        history -c
    fi
}

history -c
while true
do
add_new_command
done

标签: linuxbashterminalhistory

解决方案


更好的方法是使用内置变量来控制历史。

history -c
BASH_HISTORY=mycommands

推荐阅读