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
If specified condition is not true in if part then else part will be execute. To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
ELIF (ELSE IF) statementELIF is the keyword used for the ELSE IF statement in bash scripting. If in a loop if more than two conditions exist which can not be solved only by using IF-ELSE statement then ELIF is used. Multiple ELIF conditions can be defined inside one if-else loop.
Like in any other programming language, if , if..else , if..elif..else , and nested if statements in Bash are used to execute code based on a certain condition.
The -n
and -z
options are tests that should be used here:
if [ -n "$JAVAHOME" ]; then
echo "$JAVAHOME";
else
echo "\$JAVAHOME not set";
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With