rcaloras / bash-preexec

⚡ preexec and precmd functions for Bash just like Zsh.
MIT License
862 stars 94 forks source link

detailed bash log with preexec and precmd #148

Open alperyilmaz opened 11 months ago

alperyilmaz commented 11 months ago

Hi, as I mentioned in previous issue #147 I'm recording bash history in a custom way. As of now, I'm trying to save the command (and current directory) to a file using preexec. Can I use precmd to keep duration and exit code of the command and then also save them?

Actually, is it possible for preexec() to keep the command as variable and then pass it to precmd as input? In that case precmd() has everything (i.e. command, folder, duration, exit code) to save to a log file.

dseomn commented 11 months ago

I don't remember if it's possible to pass variables between the two, but when I wanted to do something similar, I decided to separately log when the command began and when it ended. With timestamps, so the duration can be calculated. That way if the command crashed the shell or the system, or caused the disk to run out of space, there would still be a chance that the command was logged before it started running. In case it's useful to you, here's the code I use to log shell commands with preexec and precmd: https://github.com/dseomn/dotfiles/blob/598a37a20bf5c413e634119efd8f8f922571fc60/.config/shell/interactive.d/50-history.bash#L56-L101

I think the only part that uses something other than standard bash features or bash-preexec is BPE_LAST_COMMAND_DID_BG on line 76 which is from https://github.com/dseomn/dotfiles/blob/public/.config/shell/interactive.d/20-bash-preexec.bash. https://github.com/dseomn/dotfiles/blob/public/.local/bin/shell-history is the command that actually logs the args passed to it from bash, but all the interesting bits are in bash.

dimo414 commented 11 months ago

Here's an example of capturing duration and exit code via the preexec/precmd hooks (this example actually uses the PROMPT_COMMAND and DEBUG trap directly by default, but if bash-preexec is found in the shell environment it delegates to bash-preexec instead).