我知道 Bash 有HISTSIZE
和HISTFILESIZE
变量来控制历史记录的保存时间以及保存量。我想保留我的历史记录档案。但是,如果我将上述两个变量中的任何一个设置为非常大的数字,那么搜索旧命令就会变得非常困难,而且经过足够长的时间后,它们可能会被删除。
一旦我的 bash 历史文件达到一定大小,我该如何自动存档它们,这种方法是否适用于其他日志文件(例如/var/log/auth.log
)?
答案1
#!/bin/sh
# This script creates monthly backups of the bash history file. Make sure you have
# HISTSIZE set to large number (more than number of commands you can type in every
# month). It keeps last 200 commands when it "rotates" history file every month.
# Typical usage in a bash profile:
#
# HISTSIZE=90000
# source ~/bin/history-backup
#
# And to search whole history use:
# grep xyz -h --color ~/.bash_history.*
#
KEEP=200
BASH_HIST=~/.bash_history
BACKUP=$BASH_HIST.$(date +%y%m)
if [ -s "$BASH_HIST" -a "$BASH_HIST" -nt "$BACKUP" ]; then
# history file is newer then backup
if [[ -f $BACKUP ]]; then
# there is already a backup
cp -f $BASH_HIST $BACKUP
else
# create new backup, leave last few commands and reinitialize
mv -f $BASH_HIST $BACKUP
tail -n$KEEP $BACKUP > $BASH_HIST
history -r
fi
fi
答案2
您可以使用 logrotate 来备份您的~/.bash_history
文件。
在 中为 logrotate 创建一个配置文件/etc/logrotate.d/bash_history
。
/home/YOUR_USERNAME/.bash_history {
weekly
missingok
rotate 5
size 5000k
nomail
notifempty
create 600 YOUR_USERNAME YOUR_USERNAME
}
你可以使用以下命令检查它是否有效:
sudo logrotate --force /etc/logrotate.d/bash_history
要查看文件:
ls ~/.bash_history*
我在这个网页上找到了它 https://kowalcj0.github.io/2019/05/13/logrotate-bash-history/
答案3
首先回答你的第二个问题:
Ubuntu 日志文件是已经进行处理logrotate
以使其易于管理且在尺寸限制之内。
您甚至可以“滥用”它来获取您的历史文件,它非常方便。
答案4
该解决方案保存了执行的日期时间:
mkdir ~/.logs
将其添加到您的 .bashrc 或 .bash_profile:
export PROMPT_COMMAND='if [ "$(id -u)" -ne 0 ]; then echo "$(date "+%Y-%m-%d.%H:%M:%S") $(pwd) $(history 1)" >> ~/.logs/bash-history-$(date "+%Y-%m-%d").log; fi'
在历史记录中搜索类型:
grep -h logcat ~/.logs/bash-history-2016-04*
取自https://spin.atomicobject.com/2016/05/28/log-bash-history/