I came across an interesting blog entry about maintaining a persistent history of commands across multiple bash sessions using some features of bash I was unaware of.
First there was a variable PROMPT_COMMAND which will run the command stored in the variable before presenting the new prompt.
Then there was the BASH_REMATCH variables, which store substring patterns when used with [[ ... ]] e.g.
test_string="Random string of numbers : 1234"
[[
$test_string =~ (.*)\:\ +([0-9]+)
]]
echo ${BASH_REMATCH[0]}
echo ${BASH_REMATCH[1]}
echo ${BASH_REMATCH[2]}
This snippet will output the following
Random string of numbers : 1234
Random string of numbers
1234
I have simplified the example from Eli's blog as I am not using the same format for history output , so my code in .bashrc looks like
log_bash_history()
{
[[
$(history 1) =~ ^\ *[0-9]+\ +(.*)$
]]
local command="${BASH_REMATCH[1]}"
if [ "$command" != "$HISTORY_LAST" ]
then
echo "$command" >> ~/.persistent_history
export HISTORY_LAST="$command"
fi
}
export PROMPT_COMMAND=log_bash_history
Showing posts with label command history. Show all posts
Showing posts with label command history. Show all posts
Friday, 27 September 2013
Thursday, 27 June 2013
Python Command history
I was using the python command interpreter interactively to test out some snippets of python and rather than either typing it out again, copy/paste and removing the prompt markers at the beginning of the line or loosing it entirely, I wondered if there was a way to save the command history like in bash.
Turns out there is an easy way to do this and it is referenced in the python documentation (http://docs.python.org/3/tutorial/interactive.html)
Place the startup script below in a file in your home directory such as .pystartup
and export the environment variable PYTHONSTARTUP pointing to this file
Turns out there is an easy way to do this and it is referenced in the python documentation (http://docs.python.org/3/tutorial/interactive.html)
Place the startup script below in a file in your home directory such as .pystartup
and export the environment variable PYTHONSTARTUP pointing to this file
import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(historyPath=historyPath): import readline readline.write_history_file(historyPath) if os.path.exists(historyPath): readline.read_history_file(historyPath) atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath
Labels:
command history,
python