This is not a valid BASH syntax - or better - it is not what you expect to be. The notation
$?varname expands to 1 if varname is set, expands to 0 if varname is not set, but only in C-shells!
To check if a variable is set or not in Bash, you have to use
where the -z test means "the length of string is zero".
When you use the $?MYVAR notation in Bash, it is interpreted as the concatenation of $? (the exit status of the previous command) plus the literal string "MYVAR". You can easily demonstrate it running the script with bash -x. This will report a trace of the actual commands executed by the shell:
Code:
$ bash -x test.sh
+ export MYVAR=apple
+ MYVAR=apple
+ '[' '!' 0MYVAR ']'
+ echo 'MYVAR is set to apple'
MYVAR is set to apple
As you can see, the string in red is the result of the expansion performed by the shell, as mentioned above. In summary, the correct Bash version of your script should be:
Code:
#!/bin/bash
#export MYVAR="apple"
if [ -z $MYVAR ]
then
export MYVAR="orange"
echo "MYVAR was not previously set to $MYVAR"
else
echo "MYVAR is set to $MYVAR"
fi