bash-preexec
bash-preexec copied to clipboard
preexec $1 is missing some commands
I'm recording command history in certain format into daily log files. I was using PROMPT_COMMAND to save the last command to a file. I was using echo "$(history -p \!-1)"
to save the last item from history to a file. But that is causing some problems: 1) the command is recorded in log file when next command is run. 2) due to ignored commands (ls, cd, ll, clear, etc.) "last command" approach becomes out of sync.
I discovered bash-preexec and it is exactly what I want "record the command as soon as I hit Enter with preexec()
function"
I updated by .bashrc accordingly, the concept is working but somehow preexec is missing some commands and do not record them and instead prints the previous command to log file. The ones that I noticed are;
- ignored commands, ls, ll, clear
- function definitions are not recorded in the log file (for example :
hello-world () { echo "hello world!"; }
)
Here's my old PROMPT_COMMAND:
export PROMPT_COMMAND='history -a; history -n; if [ "$(id -u)" -ne 0 ]; then echo -ne "$(date "+%Y-%m-%d.%H:%M:%S")\t$(hostname)\t$(pwd)\t"; echo "$(history -p \!-1)" >> ~/.logs/bash-history-$(hostname)-$(date "+%Y-%m-%d").log; fi'
Here's my new PROMPT_COMMAND:
export PROMPT_COMMAND='history -a; history -n;'
And here's my preexec()
function:
preexec() { echo -e "$(date "+%Y-%m-%d.%H:%M:%S")\t$(hostname)\t$(pwd)\t$1" >> ~/.logs/bash-history-$(hostname)-$(date "+%Y-%m-%d").log; }
What should I do so that whatever I write in prompt is saved to log file as soon as I hit Enter