Exporting JAVA_HOME has no effect when execute in *.sh on macOS BigSur

I have a script j16.sh with content:

export JAVA_HOME=`/usr/libexec/java_home -v 16.0.1`
echo Java 16

When I run the script on the terminal (zsh) using

./j16.sh

it prints “Java 16”, but when I call “java –version”, the version has not changed to 16.

However, when I execute the “export” line (copied from the script” directly on the terminal), the Java version gets switched, as expected.

What am I doing wrong? Apparently, executed in the script, the line has no effect – but the echo-line has?

Answer

You should use Source

source j16.sh

This will run the commands of the script rather than launching a new shell, and that will result in setting the environment .