MacOS – Reset terminal environment to start up state, not losing print of history

bashcommand linemacosterminal

This might seem like a duplicate at first sight, but bear with me for a minute.

TLDR; A quick command line way to restore the whole shell environment to the same as upon terminal startup, while not losing the print (scroll up) of the previously executed commands and their outputs.

I would really like a quick way to reset the shell environment to it's starting state, like quitting the the terminal program and starting it again (or opening a new tab). The reason that I don't want to actually quit the program and start it again is that I don't want to lose the history, ie the print of the previous commands and outputs. (Compare to clear in MATLAB, that gets rid of all variables, function definitions et.c. that you've set in that session without removing the print of previous commands and outputs.)

The usual advice people get when asking this is

source ~/.bash_profile

However, for example, this doesn't restore $PATH to the value it has when the terminal program is first opened. I have a few lines like

export PATH=$PATH:/path/to/some/useful/stuff/

in my $PATH and for every time I source, more stuff is added to my $PATH variable. Hence it is not reset to terminal startup value on source.
Same thing goes for any other variable set in that session that is not overwritten by some line in the ~/.bash_profile

I've seen people recommend the reset command too. However, that doesn't restore my $PATH to it's original value either. It stays the same as before the reset.

I am just using $PATH as an example here, the question is about resetting the whole shell environment.

A quick and reliable way to reset the shell environment in the sense I describe above would be very handy when experimenting with installations and similar things. Also seeing what the $PATH variable looks like makes me wonder what other things are not reset using source ~/.bash_profile, and it feels unreliable to use as a reset method.

Thank you for reading this far!

Any solutions folks?

Best Answer

One option for resetting the Terminal session's state except for history is to save the current history to a temp file with something like history -w ~/.history_temp, then close the Terminal window, open a new one, then read back the saved history with history -w ~/.history_temp. Optionally, you can delete the temp history file when you're done.

If you don't want to have to remember & type those commands every time, you can create aliases for them and put those in ~/.bash_profile:

alias savehistory='history -w ~/.history_temp`
alias loadhistory='history -r ~/.history_temp && rm ~/.history_temp`