Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I've tried to search in ~/.bash_history for my recent commands while in a terminal session but they just weren't there. I guess this is because I have multiple terminal sessions open.

Is there a way that I can sync (ie. sync-push or sync-write-out) the current terminal session's command history into the bash_history file (without closing the session and losing that environment)?

(It would be remotely similar in idea to how the sync command stores the file-system modifications on some embedded systems.)

I imagine I could set up bash to preserve multiple session history but the ability to push the current history buffer would still be useful in scenarios when you are working on a new machine and you accidentally forgot to set up bash the way you may would have wanted.

share|improve this question
    
I've tried history -a shell builtin command but somehow I now get 'permission denied' on the .bash_history file, after that. –  naxa May 22 at 11:30

1 Answer 1

up vote 2 down vote accepted

Add this line to .bashrc:

export PROMPT_COMMAND="history -a; history -n"

Open new termial and check.

Explanation

  • history -a append new history lines to history file.
  • history -n tell bash to read lines that is not read from history file to current history list of session.
  • PROMPT_COMMAND: contents of this variable is run as regular command before bash show prompt. So every time you execute a command, after that, history -a; history -n is executed, you bash history is synced.
share|improve this answer
    
thanks! I don't know why did I get permission denied before but with new terminals now this seems to work as expected! I guess I should normally be able to use history -a in a terminal with unmodified bashrc too. –  naxa May 22 at 11:40
    
when do one have to start to worry about the performance implications of this? (I'm thinking about low-end devices, not sure how big overhead this makes.) –  naxa May 22 at 11:42
    
Also you might already have a prompt command, in this case it is better to use export PROMPT_COMMAND="${PROMPT_COMMAND};history -a; history -n" –  Fabian May 22 at 13:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.