I am kinda wary of messing with bash history settings and I just want to write my own custom bash history. I thought about using a bash function like this:


  # write to a custom history file manually
  echo "$@" >> $HOME/my_bash_history

  command bash "$@" 


export -f bash;

but this doesn't quite work - what happens is that the command bash takes over, and things no longer go through the bash function. I need all stdin to bash to go through this bash function in order for everything to be written to a custom file. Anyone have an idea on how to do this?


What you want is a DEBUG trap (run before each command) or possibly a PROMPT_COMMAND (run before each prompt).

The trap is closer to your attempt. The basic concept is outlined in Does bash have a hook that is run before executing a command? and a polished turnkey version exists as bash-preexec.

According to its author, bash-preexec is used by Bashhub to provide "bash history in the cloud," so I'm sure it's up to the task of "bash history in a file."


You are trying to implement something equivalent to this "eternal history":

           "$(history 1)" >> ~/.bash_eternal_history'

The core idea is that history 1 (in bash) lists the last line given to bash.

$ echo "$(history 1)"
12766  2019-05-31T20:14:44+0000 echo "$(history 1)"

Which actually only has a meaningful value (not the same line) inside an script.

And; PROMPT_COMMAND executes the history command for each new line given to bash.

IMO: It doesn't seem to be a good idea to name a function bash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.