Skip to content

Instantly share code, notes, and snippets.

@smt
Forked from lavoiesl/zsh-record-history
Last active May 17, 2024 04:29
Show Gist options
  • Save smt/b4f165547d467437f2717649e41cbf02 to your computer and use it in GitHub Desktop.
Save smt/b4f165547d467437f2717649e41cbf02 to your computer and use it in GitHub Desktop.
#!/bin/zsh
# Search for, select, and execute command from history DB using FZF
# Inspired by http://junegunn.kr/2015/04/browsing-chrome-history-with-fzf/
h(){
local sep query
sep='{::}'
query="SELECT cmd, count(*) as frequency
FROM hist
GROUP BY cmd
ORDER BY time DESC, frequency DESC"
eval $(sqlite3 -separator $sep ${ZSH_RECORD_HISTORY_SQLITE} ${query} |
awk -F ${sep} '{print $1}' |
# Remove any newlines from field for display in FZF
sed ':a;{N;s/\\\n//};ba' | fzf --ansi)
}
#!/bin/zsh
# Credit: Sébastien Lavoie (https://gist.github.com/lavoiesl/b56cd4f994934afff6f9d6c445170d1a)
# Inspired by 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