I use fish shell and Gnome-Terminal Version 3.44.
When I open a new terminal I'd like it to start up in the previously-visited directory. How can I implement this via fish shell?
I use fish shell and Gnome-Terminal Version 3.44.
When I open a new terminal I'd like it to start up in the previously-visited directory. How can I implement this via fish shell?
You have a few options as to when to save the directory:
I'll use the "each time" approach for this example. First, I recommend exiting all but one terminal/fish shell. This will allow subsequent shell invocations to load the new function properly.
Create a Fish script that runs at startup:
~/.config/fish/conf.d/starting_dir.fish
:
set -q fish_most_recent_dir && [ -d "$fish_most_recent_dir" ] && cd "$fish_most_recent_dir"
function save_dir --on-variable PWD
set -U fish_most_recent_dir $PWD
end
This will:
check that the fish_most_recent_dir
variable exists, that it refers to an existing directory, and changes to it if so.
create a save_dir
function that saves the current directory to the fish_most_recent_dir
universal variable whenever the directory changes (--on-variable PWD
).
The save_dir
event function needs to be forcibly loaded at startup this way because autoload functions can't handle events in fish.
Note that if there are any other cd
statements in your startup config, they may get executed after this function. If that happens, they'll override this.
If you want to save the working directory only when Fish exits, you would change the event function to use --on-event fish_exit
instead.
set --show fish_most_recent_dir
will show the updated directory. You mention running gnome-terminal
-- Are you running that on WSLg (Windows 11) or using some other method? I just added add gnome-terminal, and it looks like the latest version on Ubuntu 18.04 was 3.28.2. But the function still fires on every cd there as well ...
Commented
May 23, 2022 at 20:07
funcsave save_dir
after creating the function and see if that helps.
Commented
May 23, 2022 at 20:10
set --show fish_most_recent_dir
produces no output (just an empty newline). When opening a new terminal, it also opens the home directory.
Commented
Aug 14, 2022 at 15:24