Skip to content

Instantly share code, notes, and snippets.

@patientzero
Last active January 3, 2023 09:52
Show Gist options
  • Save patientzero/39496387237d85c8d29d209d29957f52 to your computer and use it in GitHub Desktop.
Save patientzero/39496387237d85c8d29d209d29957f52 to your computer and use it in GitHub Desktop.
regular backup of bash_history
#!/bin/bash
# This is a script to backup your command history.
# How to use:
# 1.) create dir (mkdir ~/history) and place this script as backup_hist.sh in it.
# 2.) add daily cronjob
# to run daily at midnight, add this line to the crontab(crontab -e):
# 0 0 * * * /bin/bash ~/history/backup_hist.sh > /dev/null 2>&1
# 3.) To allow filtering of commands by date, add this to your .bashrc:
# HISTTIMEFORMAT="%d/%m/%y %T " and also here:
# hist command in non interactive shells by defautl disabled, so enable by adding historyfile
HISTTIMEFORMAT="%d/%m/%y %T "
HISTFILE=~/.bash_history
set -o history
yesterday="date -d yesterday +%d/%m/%y"
history | grep $($yesterday) > /PATH_TO_HISTORY_BACKUP/$(date -d "yesterday" +%d-%m-%y)_history
@patientzero
Copy link
Author

Helpful configuration(put in .bashrc) to use same history file over all sessions and add a timestamp to the history:

HISTCONTROL=ignoreboth:erasedups

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=10000
HISTFILESIZE=10000
HISTTIMEFORMAT="%d/%m/%y %T "

# append to history, don't overwrite it
shopt -s histappend
# Save and reload the history after each command finishes
export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment