I wrote a bash script to set the environment variable VAR if it is currently not set:
example.sh
#!/bin/bash
if [ -z $VAR ]; then
export VAR=abc
fi
Now I type this in the command line: ./example.sh && echo $VAR. I expect abc, but the result is blank. Why?
source ./example.sh && echo $VAR. Your command sets the environment variable within the context ofexample.shscript (which runs in a subshell): this cannot affect the parent environment.[ -z "$VAR" ]andecho "$VAR".