What is wrong with my shell script in SunOS, runs fine on other linux flavours

AabinGunz picture AabinGunz · Oct 20, 2011 · Viewed 7.2k times · Source

Please can someone identify what is the problem in my shell script, it works fine on other Linux systems except on Sunos below is my output

drifter% cat run.sh
#!/bin/sh -x
if [ ! $JAVA_HOME ] || [ $JAVA_HOME == "" ]
then
    echo Enter path to JAVA HOME:
    read JAVA_HOME
fi

if [ ! -f $JAVA_HOME/bin/java ]
then
echo "JAVA_HOME variable does not point to a valid java instance"
exit 1
fi

echo "Using JAVA_HOME: "$JAVA_HOME
JAVA_BIN=$JAVA_HOME/bin
ver=`$JAVA_HOME/bin/java -version 2>&1 | head -1 | awk '{print $NF}' | cut -d'.' -f2`

if [ $ver -ge 5 ]
then
    JAVA_LIB=`pwd`/lib
    export JAVA_LIB

    $JAVA_BIN/java -cp ./lib/a-jdbc-sqlserver-4.2.1.jar:./lib/a-jdbc-db2-4.2.1.jar:./lib/ilmInit.jar:./lib/db2jcc.jar:./lib/db2jcc_license_cisuz.jar:./lib/db2jcc_license_cu.jar:./lib/csm-runtime-1.0.jar:./lib/csm-dbutil-1.0.jar:./lib/classes12_g.jar:./lib/commons-beanutils-1.8.3.jar:./lib/commons-cli-1.2.jar:./lib/commons-exec-1.1.jar:./lib/log4j-1.2.8.jar:./lib/groovy-all-1.8.1.jar -Dlog4j.configuration=com/a/csm/log4j.xml -Dendorsed_plugins_dir=./plugins InitValues $@

else
    echo Current JDK $ver
    echo "Expected JDK 1.5 or later. Please fix your JAVA HOME and try again."
    exit 1
fi
drifter% ./run.sh
+ [ ! ]
./run.sh: test: argument expected
drifter%

Note: I am using csh

Update

I changed "$JAVA_HOME" everywhere

but still i get

drifter% ./run.sh
+ [ ! /home/ilma1/java16/java ]
+ [ /home/ilma1/java16/java ==  ]
./run.sh: test: unknown operator ==

Answer

Keith Thompson picture Keith Thompson · Oct 20, 2011

Probably $JAVA_HOME isn't set. An unset variable normally expands to an empty string, so this:

if [ ! $JAVA_HOME ] || [ $JAVA_HOME == "" ]

is equivalent to this:

if [ ! ] || [ == "" ]

which is a syntax error. ([ is another name for the test command; it's usually a symbolic link.)

Try quoting the variable name:

if [ "$JAVA_HOME" == "" ]

And if you set $JAVA_HOME in response to the prompt, you probably want to export it. (Actually I'm not sure of that; does java depend on $JAVA_HOME being set?)

EDIT:

Ok, it looks like $JAVA_HOME was set.

For the test (or [) command, the string equality operator is =, not ==.

Try:

if [ "$JAVA_HOME" = "" ]

EDIT2:

This:

if [ -z "$JAVA_HOME" ]

is probably better (see @n.m's answer).