Linux Bash/sh 'if else' 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7020914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:38:00  来源:igfitidea点击:

Bash/sh 'if else' statement

linuxbashshell

提问by AabinGunz

I want to understand the if elsestatement in shscripting.

我想了解脚本中的if else语句sh

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

所以我写了下面来找出环境中是否设置JAVA_HOME。我写了下面的脚本

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

This my output to env:

这是我的输出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

采纳答案by duskwuff -inactive-

You're running into a stupid limitation of the way shexpands arguments. Line 3 of your script is being expanded to:

您遇到了sh扩展参数方式的愚蠢限制。脚本的第 3 行正在扩展为:

if [ != ]

Which shcan't figure out what to do with. Try this nasty hack on for size:

sh不知道该怎么办。试试这个讨厌的大小:

if [ x$JAVA_HOME != x ]

Both arguments have to be non-empty, so we'll just throw an xinto both of them and see what happens.

两个参数都必须是非空的,所以我们只需将一个x放入它们两个中,看看会发生什么。

Alternatively, there's a separate operator for testing if a string is non-empty:

或者,有一个单独的运算符用于测试字符串是否为非空:

if [ !-z $JAVA_HOME ]

(-ztests if the following string is empty.)

-z测试以下字符串是否为空。)

回答by Kracekumar

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

回答by sente

The -nand -zoptions are tests that should be used here:

-n-z选项是应该在这里使用的测试:

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

回答by William Pursell

Note that if you want to determine if a variable is set, you probably do not want to use either if/else or test ([). It is more typical to do things like:

请注意,如果您想确定是否设置了变量,您可能不想使用 if/else 或 test ([)。更典型的做法是:

# 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}