save bash history, regularly

9

3

I have bash set up to save history, to a file. It does this whenever bash exits [properly]. As sometimes bash does not exit properly the history is lost.

So the question is can I set up bash to save history more regularly?


I am running Debian Gnu (version 6, Squeeze) with a Linux kernel.

bash version: GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)

ctrl-alt-delor

Posted 2012-09-19T14:55:28.813

Reputation: 1 886

Answers

8

save this to your bash_profile or bashrc

shopt -s histappend

PROMPT_COMMAND="history -a;$PROMPT_COMMAND"

d4v3y0rk

Posted 2012-09-19T14:55:28.813

Reputation: 1 187

Is this still a valid answer? In my system, there is an entry shopt -s histappend under /etc/bash/bashrc. Still, any unclean exit of running shells, loses its command line history. – Nikos Alexandris – 2019-02-19T01:07:25.343

-1

It's possible your $HISTFILE is owned by root. Assuming your are using bash as your login shell. Here's how to check:

$ [ -z $HISTFILE ] && echo need to set HISTFILE || ls -l $HISTFILE
-rw------- 1 root root 36639 May 21 19:48 /home/joeb/.bash_history

The default for HISTFILE should be ~/.bash_history, if you see the error "need to set HISTFILE" or if $HISTFILE is not ~/.bash_history, then you should check ~/.profile or ~/.bash_profile or ~/.bashrc to make sure it's not getting set or reset incorrectly.

Normally, it's just owned by root, so just reset it:

$ chown joeb.joeb $HISTFILE
$ ll $HISTFILE
-rw------- 1 joeb joeb 36639 May 21 19:48 /home/joeb/.bash_history

Logout then login.

$ history

Should show the last set of commands entered before the file was owned by root, followed by the commands entered after the file ownership was changed.

focused4success

Posted 2012-09-19T14:55:28.813

Reputation: 99

3Since OP says that the history is saved when bash exits normally, his issue has nothing to do with the permissions. Perhaps your answer could still be useful for someone who has troubles with bash history. – Dmitry Grigoryev – 2015-05-22T13:23:50.767