Skip to content

Instantly share code, notes, and snippets.

@lavoiesl
Created August 5, 2016 18:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lavoiesl/b56cd4f994934afff6f9d6c445170d1a to your computer and use it in GitHub Desktop.
Save lavoiesl/b56cd4f994934afff6f9d6c445170d1a to your computer and use it in GitHub Desktop.
#!/bin/zsh
# Inspired from https://github.com/fredsmith/history-db
ZSH_RECORD_HISTORY_SQLITE="${ZSH_RECORD_HISTORY_SQLITE:-$HOME/.zsh_history.sqlite}"
if [[ -x "$(which sqlite3 2>/dev/null)" ]]; then
zsh_record_history_preexec() {
zsh_record_history_cmd="$1"
zsh_record_history_time="$(date +%s)"
}
zsh_record_history_precmd() {
local duration
local escaped_cmd
if [ -n "${zsh_record_history_cmd}" -a "${zsh_record_history_time}" -gt 0 ]; then
escaped_cmd="$(echo ${zsh_record_history_cmd} | sed "s/'/''/g")"
duration=$(( $(date +%s) - ${zsh_record_history_time} ))
sqlite3 "${ZSH_RECORD_HISTORY_SQLITE}" <<SQL
INSERT INTO hist (user, cmd, time, duration) VALUES (
'${USER}',
'${escaped_cmd}',
'${zsh_record_history_time}',
'${duration}'
);
SQL
fi
zsh_record_history_cmd=
}
if [ ! -f "${ZSH_RECORD_HISTORY_SQLITE}" ]; then
sqlite3 "${ZSH_RECORD_HISTORY_SQLITE}" <<SQL
CREATE TABLE options (name TEXT PRIMARY KEY, value TEXT);
INSERT INTO options VALUES ('schema_version', 1);
CREATE TABLE hist (id INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT, cmd TEXT, time INTEGER, duration INTEGER);
SQL
fi
[[ -z $preexec_functions ]] && preexec_functions=()
preexec_functions=($preexec_functions zsh_record_history_preexec)
[[ -z $precmd_functions ]] && precmd_functions=()
precmd_functions=($precmd_functions zsh_record_history_precmd)
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment