0

I executed the command below in a BASH shell.

export PROMPT_COMMAND='echo "$BASH_COMMAND" >> $HOME/my_bash_history'

but everytime I type something in the shell and hit return, I just get one more line my_bash_history file which fills up with:

echo "$BASH_COMMAND" >> $HOME/my_bash_history
echo "$BASH_COMMAND" >> $HOME/my_bash_history
echo "$BASH_COMMAND" >> $HOME/my_bash_history
echo "$BASH_COMMAND" >> $HOME/my_bash_history
echo "$BASH_COMMAND" >> $HOME/my_bash_history
echo "$BASH_COMMAND" >> $HOME/my_bash_history

anybody know why that's happening?

muru
  • 72,889
  • 1
    @RuiFRibeiro I don't think this is a duplicate. The asker here is using single quotes (as far as I can tell, correctly), but the action is not being interpolated at use-time as explained and expected in the "duplicate". – Chris Davies Jun 03 '19 at 08:32

1 Answers1

2

As Rui pointed out, "Anything inside ' is not evaluated." Or, as stated by the BASH manual,

Enclosing characters in single quotes preserves the literal value of each character within the quotes.

As a solution to accompany the answer, one way to record the history with PROMPT_COMMAND follows.

export PROMPT_COMMAND='echo $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//") >> $HOME/my_bash_history'
Christopher
  • 15,911
  • thanks - seems weird that I have to look into history to get the previous command - since there is no new command yet, I would think $BASH_COMMAND would still be set to the previous command? idk – Alexander Mills May 31 '19 at 20:11
  • can you explain what the sed command is doing? I can accept once I know for sure what it's doing thx – Alexander Mills May 31 '19 at 20:45
  • from what I can tell, this won't let me capture the PID of the previous command or the exit code, or anything useful like that - although perhaps there's an option to put that into the bash history? – Alexander Mills May 31 '19 at 21:13
  • 1
    I remember answering different questions that might provide more clues. https://unix.stackexchange.com/questions/518909/logging-shell-activity and https://unix.stackexchange.com/questions/207813/how-to-log-every-command-typed-into-bash-and-every-file-operation/. – Christopher May 31 '19 at 22:29
  • @AlexanderMills Oops... missed your sed question. I may have incorrectly surmised that you are using Linux; but, in Linux, at least, the sed command removes the command history number and the white space surrounding the command history number. – Christopher Jun 03 '19 at 16:36