Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I point the 'history' command to an alternate file?

On my development machine, I have a number of different environments, each of which maintaining an own history file with a dedicated name. This is a customer requirement which I can not change.

If I have activated one of these environments, a 'history' command will always list the contents of the current environments history-file which is ok.

However, if I want to look up something in the history of another environment, I can only do this by opening a new shell and loading the respective environment. But what I want to do is to tell 'history' from which file it should read it's input without opening a new session and loading the environment in question.

Just 'grep'ing the alternative history-file is not a satisfying option as I want the entire output (e.g. timestamps) to be formatted properly.

The question is: How can I point 'history' to process an alternative file? Trying with

$ HISTFILE=/path/to/other-histfile history

didn't help, nor did

$ export HISTFILE=/path/to/other-histfile; history

I could write a perl script to do produce the oputput I want. But perhaps there is a way to do this out of the box?

EDIT: An environment is activated by a script which sources all settings which are relevant for the history processing.

useEnv() is an alias which basically looks like this:

useEnv()
{
export HISTFILE=/some/directory/.bash_history.$ENVNAME
PROMPT_COMMAND="history -a; $PROMPT_COMMAND"
export HISTCONTROL=ignoreboth
}

EDIT, SOLUTION: KamilCuk had the solution which works for me, see his answer below. Here is my summary:

  • You can write an alias or a script which first clears [-c] the history list (but leaves $HISTFILE untouched), and then reads [-r] the alternative history file.
  • Upon the next history call the content of the alternative file is displayed.
  • Then, clear the history again and read back $HISTFILE
  • like so:

$ history -c -r /path/to/otherfile; history; history -c -r $HISTFILE

like image 843
emax Avatar asked Nov 21 '25 12:11

emax


1 Answers

HISTFILE is the file where the command history is saved (and read on startup, and also it's the default for history command when no filename argument is given, but mostly it's for saving).

Clear current history list and then read another history file to the current history list:

history -c
history -r /path/to/other-histfile

You might want to modify HISTFILE too, so it does not get saved.

like image 61
KamilCuk Avatar answered Nov 23 '25 02:11

KamilCuk