Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash/sh 'if else' statement

Tags:

linux

bash

shell

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
like image 271
AabinGunz Avatar asked Aug 11 '11 04:08

AabinGunz


People also ask

How do you write an if-else condition in shell script?

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.

Can you do else if in Bash?

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.

Does Bash have Elif?

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.


1 Answers

The -n and -z options are tests that should be used here:

if [ -n "$JAVAHOME" ]; then
    echo "$JAVAHOME";
else
    echo "\$JAVAHOME not set";
fi
like image 188
sente Avatar answered Oct 21 '22 06:10

sente