10

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)

3 Answers 3

8

save this to your bash_profile or bashrc

shopt -s histappend

PROMPT_COMMAND="history -a;$PROMPT_COMMAND"

1
  • 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. Feb 19, 2019 at 1:07
0

I decided to use export PROMPT_COMMAND='history -a' in my .bash_aliases which writes from the history list in memory to the history file at every prompt. I had some problems with deduplication, but were resolved. I did resort to also using a cron.daily and monthly to backup the file. If the terminal is interrupted without exiting, it wont be saved. Even trapping the exit wont work. Unfortunately, the cron job cant save the history list either, which is stored in memory. I could not find a way to send a command to the current running shell to do history -w write from list to file. That could be used, but there would have to be a separate one for each shell open in a tab if one wanted to keep the work separate. If not, there is another link discussing how to write on every prompt while also deduplicating.

https://unix.stackexchange.com/questions/697314/any-way-to-resolve-export-prompt-command-history-a-and-histcontrol-ignored/720637#720637

-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.

1
  • 4
    Since 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. May 22, 2015 at 13:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .