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?

2 Answers 2

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

2
  • WARNING : If you arge going to use BashHub I would suggest running your own server using the software at github.com/nicksherron/bashhub-server . Otherwise you can not be sure that your history is private.
    – Garo
    Commented May 8, 2023 at 14:45
  • Well said and, to be clear, I was recommending only bash-preexec and citing Bashub as a reference. Putting bash history in the cloud is probably not a good idea at all. Commented May 9, 2023 at 5:10
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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .