我知道 Bash 有HISTSIZE和HISTFILESIZE变量来控制历史保存的时间和保存的数量。我想保留我的历史档案。但是,如果我将上面提到的两个变量中的任何一个设置为一个非常大的数字,就会使搜索旧命令变得非常困难,并且在足够长的时间之后它们可能会被删除。
一旦我的 bash 历史文件达到一定大小,我如何自动归档它们,这种方法是否适用于其他日志文件(例如/var/log/auth.log)?
#!/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
Run Code Online (Sandbox Code Playgroud)
摘自“ https://lukas.zapletalovi.com ”上的“再也不会丢失您的 bash 历史记录”。