I use emacs for almost everything, but when I run shell M-x shell
and then exit from emacs, the history is not saved, I've tried (savehist-mode 1)
for this purpose but it doesn't seem to work, is there any way to save the history of the commands used in emacs and use them when I use shell outside of emacs?
1 Answer
savehist-mode
isn't applicable here; the reason you're having this trouble is because Bash, by default, will only write to the history file when its in-memory history buffer is full or on exit, and the latter only if it exits cleanly -- that is, a Bash process which is killed rather than exiting will never write recent commands to the history file.
To work around the problem, ensure that you always cleanly finish your shell session by executing logout
or exit
, or typing C-d
at the prompt, before killing your shell buffers; this will give Bash a chance to write the history file before exiting.
Also, see the Bash FAQ on history file management, for some ideas on how to have Bash write each command to history as soon as it's executed; once you've gotten that working, you need no longer worry about logging out of your shells before you kill their buffers, but can C-x k
with wild abandon.
-
2As suggested by the bash FAQ, setting PROMPT_COMMAND="history -a" in my .bashrc file worked nicely for me, thanks.– wyttenAug 26, 2013 at 17:30
~/.bash_history
, just as whenbash
runs in a more ordinary terminal emulator; I'm not sure why you would be seeing different behavior. What shell are you running, and how is it configured with regard to history?M-x shell
and when I kill the buffer it doesn't save the history, the only attempt I did was to put(savehist-mode 1)
in.emacs
file but still I cannot see the commands used in emacssavehist-mode
applies by default only to minibuffer input, and is thus not applicable here (though you might find it useful in general). Most likely your login shell isbash
, and I've frequently found that by defaultbash
won't save history until the process exits cleanly, i.e., on logout -- which doesn't happen if you kill the shell buffer withC-x k
or similar; when that happens, the shell process is killed, rather than exiting on its own. If that's what you do right now, try doinglogout
orexit
in your shell buffer before killing the buffer, and see if history gets saved.ps -p $$
at the command line; the value under 'CMD' in the output is the shell you're using. Most likely it'll bebash
, but if it's not, add a comment to say what it is, and someone may be able to assist you further from there -- I only usebash
myself, so can't help much if you're using anything else.)