1

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:

bash(){

  # 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?

4

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."

| improve this answer | |
2

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

export HISTTIMEFORMAT="%s "
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo $$ $USER \
           "$(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.

| improve this answer | |

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.