If I want to switch opam switch, should I use eval $(opam env --switch=<switch_name> --set-switch) or opam switch set <switch_name>? why are there two ways to do this?

I noticed that there were two ways to change switches. Why? What are the pros and cons and which one should one be using? which one is standard/best practice?

Is it true that this is the main difference?

The main difference between the two approaches is that opam switch set only affects opam, while eval $(opam env ...) affects the whole shell environment. So if you only need to use opam packages, you can use opam switch set . If you want to use the packages with other tools, you should use eval $(opam env ...) .

I don’t do either of those, I always do:

opam switch blabla
eval $(opam env)

For local development at least you do want to set the correct environment variables. Although there are some loopholes where even opam env doesn’t: `opam env` does not recalculate all paths correctly when local switch is moved · Issue #5423 · ocaml/opam · GitHub

I am a bit puzzled,

I have the following session:

oyer@ak-serveur2:~$ opam switch default
loyer@ak-serveur2:~$ type ocaml
ocaml est /home/loyer/.opam/default/bin/ocaml
loyer@ak-serveur2:~$ opam switch 5.0.0
loyer@ak-serveur2:~$ type ocaml
ocaml est /home/loyer/.opam/5.0.0/bin/ocaml

I don’t know how bash did know it has to upgrade its environment. The PATH has changed between the two switch command.

If I recall correctly when you install recent versions of opam it encourages you to let it install a switch hook so that it runs the eval $(opam env) automatically when you change switches. You can check your shell startup script to see if you have the hook installed.

Oh yes, the following code is execute at the start of bash:

PROMPT_COMMAND="_opam_env_hook;

Evil. I do very much hope this always stays optional. I’m already staying away from Nix because of this; I don’t want Ocaml to be next.

related but how to do change switch from within python: Is eval $(opam env --switch={switch} --set-switch) equivalent to opam switch set switch? and What is the difference between eval $(opam env --switch={switch} --set-switch) and opam switch set SWITCH? - Stack Overflow