Skip to content
Advertisement

Bash/sh ‘if else’ statement

I want to understand the if else statement in sh scripting.

So I wrote the below to find out whether JAVA_HOME is set in the environment or not. I wrote the below script

#!/bin/sh
if [ $JAVA_HOME != "" ]
then
    echo $JAVA_HOME
else
    echo "NO JAVA HOME SET"
fi

This my output to env:

sh-3.2$ env

SHELL=/bin/csh
TERM=xterm
HOST=estilor
SSH_CLIENT=10.15.16.28 4348 22
SSH_TTY=/dev/pts/18
USER=asimonraj
GROUP=ccusers
HOSTTYPE=x86_64-linux
PATH=/usr/local/bin:/bin:/home/asimonraj/java/LINUXJAVA/java/bin:/usr/bin
MAIL=/var/mail/asimonraj
PWD=/home/asimonraj/nix
HOME=/home/asimonraj
SHLVL=10
OSTYPE=linux
VENDOR=unknown
LOGNAME=asimonraj
MACHTYPE=x86_64
SSH_CONNECTION=100.65.116.248 4348 100.65.116.127 22
_=/bin/env

But I get the below output:

sh-3.2$ ./test.sh
./test.sh: line 3: [: !=: unary operator expected
NO JAVA HOME SET

Advertisement

Answer

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.)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement