Skip to content

Instantly share code, notes, and snippets.

@cemiu
Last active February 5, 2025 15:29
Show Gist options
  • Save cemiu/d0773cbc76ae9e9ae1b200653ef41caa to your computer and use it in GitHub Desktop.
Save cemiu/d0773cbc76ae9e9ae1b200653ef41caa to your computer and use it in GitHub Desktop.
bash better logging of commands
trap 'export CMD_START_TIME=$(date +%s)' DEBUG
precmd() {
local exit_code=$?
[ -z "$CMD_START_TIME" ] && return
local now=$(date +%s)
local elapsed=$(printf "%dh%d" $(( (now - CMD_START_TIME) / 3600 )) $(( (now - CMD_START_TIME) % 3600 / 60 )))
local start_time=$(date -d "@${CMD_START_TIME%.*}" +'%Y-%m-%d %H:%M:%S')
local cmd=$(HISTTIMEFORMAT= history 1 | sed 's/^ *[0-9]* *//')
skips=(ls "ls *" ll "*.bashrc*" exit history "cd *" vim "vim *")
for skip in "${skips[@]}"; do case "$cmd" in "$skip") unset CMD_START_TIME; return ;; esac; done
printf "%s ; %s ; %s ; %s ; %s\n" \
"$start_time" "$(hostname)" "$elapsed" "$exit_code" "$cmd" \
>> ~/.command.log
unset CMD_START_TIME
}
PROMPT_COMMAND=precmd

Comments are disabled for this gist.