Anthony Accioly
Anthony Accioly

Reputation: 22471

How can I setup IntelliJ to remember Git Bash current working directory between sessions?

I'm running IntelliJ 2018.3 on Windows 7, as well as openSUSE Leap 15. Under Windows 7, I've configured IntelliJ to use Git Bash, i.e., in Settings, under Tools -> Terminal, I'm setting Shell path to:

C:\Program Files (x86)\Git_2.17.1\bin\bash.exe

One of IntelliJ's new features is the ability to save and reload terminal sessions (see this link).

It works perfectly with openSUSE, however, on Windows, while the terminal tab names are correctly restored, I always end up with a new shell.

Is there a way to make IntelliJ and Git Bash play well together so that I can retain the current working directory and shell history after restarting IntelliJ?

Upvotes: 2

Views: 2849

Answers (2)

Anthony Accioly
Anthony Accioly

Reputation: 22471

Here's a possible workaround. It was heavily inspired by VonC's answer, as well as other answers to the question that he mentioned.

~/.bashrc

if [[ -v __INTELLIJ_COMMAND_HISTFILE__ ]]; then
    __INTELLIJ_SESSION_LASTDIR__="$(cygpath -u "${__INTELLIJ_COMMAND_HISTFILE__%history*}lastdir${__INTELLIJ_COMMAND_HISTFILE__##*history}")"

    # save path on cd
    function cd {
        builtin cd $@
        pwd > $__INTELLIJ_SESSION_LASTDIR__
    }

    # restore last saved path
    [ -r "$__INTELLIJ_SESSION_LASTDIR__" ] && cd $(<"$__INTELLIJ_SESSION_LASTDIR__")
fi

I don't like the fact that I had to wrap the cd command, however Git Bash does not execute ~/.bash_logout unless I explicitly call exit or logout; unfortunately due to this limitation, the .bash_logout variant is inadequate for the mentioned scenario.

The workaround above also leave small junk files inside __INTELLIJ_COMMAND_HISTFILE__ parent dir, however, I couldn't do any better.

Additionally I've opened a ticket in Jetbrain's issue tracker. There are many different shells that may benefit from official support. It would be great if JetBrains could eventually support and popular terminals like , and . The only shell that currently works out of the box for me is .

Upvotes: 2

VonC
VonC

Reputation: 1327364

You can try and setup your Git for Windows bash to remember the last used path for you, as seen in "How can I open a new terminal in the same directory of the last used one from a window manager keybind?"

For instance:

So instead of storing the path at every invocation of cd the last path can be saved at exit.

My ~/.bash_logout is very simple:

echo $PWD >~/.lastdir

And somewhere in my .bashrc I placed this line:

[ -r ~/.lastdir ] && cd $(<~/.lastdir)

That does not depend on Intellij IDEA directly, but on the underlying bash setup (here the Git for Windows bash referenced and used by Intellij IDEA.

Upvotes: 3

Related Questions