I have a custom cd function that looks like:
function cd -d "cd with auto conda activation"
# set -gx OLDPWD (pwd) <-- uncommenting this does not resolve issue
builtin cd $param $argv
if test -f (pwd)/.condaconfig
set -gx CONDACONFIGDIR (pwd)
conda activate (cat .condaconfig)
else if [ -n "$CONDACONFIGDIR" ]
if [ -n (string match -q -- "*$CONDACONFIGDIR*" (pwd)) ]
set -gx CONDACONFIGDIR ""
conda deactivate
end
end
end
but with this active, I cannot use cd - to change to the previous directory.
Have I implemented builtin wrong? I feel like I'm missing something here.
I have an equivalent custom function in bash which works fine and continues setting/using OLDPWD - fish seems to use something else to keep track of previous directory, but it's not an environment variable (ie. doesn't show up in the output of env)
-
Thanks for sharing your solution, but please move it to an answer rather than edit it into the question. That way other users can evaluate it separately from the question (and upvote it accordingly). Thanks!NotTheDr01ds– NotTheDr01ds2024年08月21日 21:18:10 +00:00Commented Aug 21, 2024 at 21:18
2 Answers 2
That is a bit tricky. Took me a moment to spot the problem ... From cd --help:
Fish also ships a wrapper function around the builtin cd that understands cd - as changing to the previous directory.
In other words,the cd - functionality isn't handled by the cd builtin itself. If you type cd, you'll see the actual function that is getting called.
So when you create a new function cd, you are overriding the Fish shell cd function, which is why you lose the ability to cd -.
I'd recommend copying the Fish cd to a new function with:
functions --copy cd cd_wrapper
Then defining your cd which will call that function (rather than the builtin). Replace:
builtin cd $param $argv
With:
cd_wrapper $argv
I'm not sure where the $param is coming from in your original version above, so adjust as needed.
Side-note: I would probably be trying to use an event-handler on this rather than overriding cd itself. E.g.:
function conda_activate --on-variable PWD
That will activate on every directory change, and you should be able to incorporate most of your existing function into that.
1 Comment
--copy option a try just for learning purposes, but the event handler is something i hadn't even considered, and does the job perfectly. Marked as accepted answer!For posterity - my final implementation of NotTheDr01ds' accepted answer:
# from:
# https://gitlab.com/glass-ships/glass-fish/functions/custom_functions.fish
function conda_activate --on-variable PWD -d "activate conda env"
if [ -f (pwd)/.condaconfig ]
set -gx CONDACONFIGDIR (pwd)
conda activate (cat .condaconfig)
end
if not [ (string match "*$CONDACONFIGDIR*" (pwd)) ]
set -e CONDACONFIGDIR
conda deactivate
end
end