Skip to content

Instantly share code, notes, and snippets.

@Bachsau
Last active February 15, 2023 14:26
Show Gist options
  • Save Bachsau/6d58bf0b9673ca564a0cf4e32a9af21f to your computer and use it in GitHub Desktop.
Save Bachsau/6d58bf0b9673ca564a0cf4e32a9af21f to your computer and use it in GitHub Desktop.
Bash history backup script
#!/bin/bash --login
# Make a backup of the user's Bash history
if [ -z "${HISTFILE}" ]; then
cd "${HOME}"
hfile='.bash_history'
else
cd "${HISTFILE%/*}"
hfile="${HISTFILE##*/}"
fi
if [ -f "${hfile}" ]; then
hsize=$(stat -c '%s' "${hfile}")
bfile="${hfile}~"
elif [ -e "${hfile}" ]; then
echo "${PWD}/${hfile} is not a regular file. Aborting." >&2
exit 1
else
echo "${hfile} not found in ${PWD}. Aborting." >&2
exit 1
fi
if [ -f "${bfile}" ]; then
bsize=$(stat -c '%s' "${bfile}")
elif [ -e "${bfile}" ]; then
echo "${PWD}/${bfile} is not a regular file. Aborting." >&2
exit 1
else
bsize=0
fi
if [ ${bsize} -gt ${hsize} ]; then
echo "Backup is larger than current history. Aborting." >&2
exit 1
fi
cp -fp "${hfile}" "${bfile}"
@Bachsau
Copy link
Author

Bachsau commented Jul 17, 2020

If you value your history, call this from your personal crontab.

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