Log all (fish) commands

Bryan Lott published on
2 min, 215 words

Log all non-sudo commands in fish-shell

All credit (and inspiriation) to:

  • https://www.justinjoyce.dev/save-your-shell-history-to-log-files/ (zsh version)
  • https://spin.atomicobject.com/2016/05/28/log-bash-history/ (bash version)

tl;dr:

Copy this into your ~/.config/fish/fish.config file:

# log every command
function cmd_log --on-event fish_preexec
  if test (id -u) -ne 0 # if we're already sudo, don't log
    echo $(date "+%Y-%m-%d.%H:%M:%S"): $(pwd): $argv >> ~/.logs/cmd-history-$(date "+%Y-%m-%d").log
  end
end

Explanation

Note: I'm no fish/bash/zsh scripting expert so take this with a grain of salt!

  • function cmd_log: Create a new fish function.

    • --on-event fish_preexec: Fire this function before every command.
  • if test (id -u) -ne 0: If we're not already sudo, then log. Note, this won't prevent sudo ls commands from being logged as we weren't sudo at the time the command started.

  • echo: Don't run, instead spit the output out.

    • $(date "+%Y-%m-%d.%H:%M:%S"): Current date/time in descending format (sortable).
    • $(pwd): Print the working directory.
    • $argv: Grab the entire command and all args.
    • >>: Append stdout (the entire echo command) to the end of...
    • ~/logs/cmd-history-$(date "+%Y-%m-%d"): Today's log file.
  • end: End the if statement.

  • end: End the function.