Bash/sh 'if else' statement
Note that if you want to determine if a variable is set, you probably do not want to use either if/else or test ([). It is more typical to do things like:
# Abort if JAVA_HOME is not set (or empty) : ${JAVA_HOME:?JAVA_HOME is unset}
or
# report the value of JAVA_HOME, or a default value echo ${JAVA_HOME:-default value}
or
# Assign JAVA_HOME if it is unset (or empty) : ${JAVAHOME:=default value}
if [ -z $JAVA_HOME ]
then
echo $JAVA_HOME
else
echo "NO JAVA HOME SET"
fi
You're running into a stupid limitation of the way sh
expands arguments. Line 3 of your script is being expanded to:
if [ != ]
Which sh
can't figure out what to do with. Try this nasty hack on for size:
if [ x$JAVA_HOME != x ]
Both arguments have to be non-empty, so we'll just throw an x
into both of them and see what happens.
Alternatively, there's a separate operator for testing if a string is non-empty:
if [ !-z $JAVA_HOME ]
(-z
tests if the following string is empty.)
The -n
and -z
options are tests that should be used here:
if [ -n "$JAVAHOME" ]; then
echo "$JAVAHOME";
else
echo "\$JAVAHOME not set";
fi