简体   繁体   English

Bash/sh 'if else' 语句

[英]Bash/sh 'if else' statement

I want to understand the if else statement in sh scripting.我想了解sh脚本中的if else语句。

So I wrote the below to find out whether JAVA_HOME is set in the environment or not .所以我写了下面的内容来了解环境中是否设置了 JAVA_HOME 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 :这是我的 output 到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:但我得到以下 output:

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

You're running into a stupid limitation of the way sh expands arguments.您遇到了sh扩展 arguments 方式的愚蠢限制。 Line 3 of your script is being expanded to:您的脚本的第 3 行正在扩展为:

if [ != ]

Which sh can't figure out what to do with.哪个sh不知道该怎么办。 Try this nasty hack on for size:试试这个讨厌的 hack 大小:

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. arguments 都必须是非空的,所以我们只需将x扔到它们中,看看会发生什么。

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.) -z测试以下字符串是否为空。)

if [ -z $JAVA_HOME  ]  
then  
    echo $JAVA_HOME  
else  
    echo "NO JAVA HOME SET"  
fi

The -n and -z options are tests that should be used here: -n-z选项是应该在这里使用的测试:

if [ -n "$JAVAHOME" ]; then
    echo "$JAVAHOME";
else
    echo "\$JAVAHOME not set";
fi

Note that if you want to determine if a variable is set, you probably do not want to use either if/else or test ([).请注意,如果您想确定是否设置了变量,您可能不想使用 if/else 或 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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM