首页 > 解决方案 > 如何使用 shell 脚本在文件中写入历史记录

问题描述

我做了一个长时间的操作,所以我想把我的历史记录并放入一个文件“text.txt”然后我 rm 历史记录,但它不起作用,我不知道为什么。

#!/bin/bash


while true
do
     history -r
     history >> root/history.txt
     echo "history.txt rempli" &
     echo "test automatise" >> history.txt
     rm history
    sleep 10
done

它只写“测试自动化”,历史是橙色的,但 bash 告诉我他不能 rm 历史,因为他不知道。

我做 ./test.sh & 当我想启动脚本时。

谢谢 !!

标签: linuxbashshell

解决方案


rm history将尝试删除历史文件或目录,它可能不存在并且会抛出错误,而是清除您的历史记录history -c

history 不起作用,因为它没有在当前的 shell 脚本中运行,你可以让它工作source

#!/bin/bash


while true
do
     history -r
     history >> root/history.txt
     echo "history.txt rempli" &
     echo "test automatise" >> history.txt
     history -c
    sleep 10
done

然后运行

$ source test.sh &

了解有关来源的更多信息:https ://superuser.com/questions/46139/what-does-source-do

详细了解为什么没有源代码就无法运行历史:https ://unix.stackexchange.com/questions/5684/history-command-inside-bash-script


推荐阅读