I have the following bash script (named “env.bash”) to be consumed by the source command:
#!/bin/bash
FOO=/some/path
Then I have the following bash script (named “compile.bash”):
#!/bin/bash
if [ -z "$FOO" ]; then
echo "Need to set FOO, did you forget to source env.bash?"
exit 1
fi
./compile-something
However, if I do:
source env.bash
./compile.bash
I get “Need to set FOO”, why? If I echo $FOO I can see its value just fine.
This should work. The reason is that a shell script will run in a sub-shell, which has its own copy of the environment; the variables of the super-shell are not normally visible. When you perform an
export, you will make the copies of the exported variables available to sub-shells.EDIT: Removed inaccuracies; also, thanks @DonCallisto for a good point.