将 Bash 字符串文字与局部变量进行比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17157162/
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-09-18 05:42:43  来源:igfitidea点击:

Compare a Bash string literal to a local variable

bash

提问by Anderson Green

#!/bin/bash
function getComment(){
    local lang=;
    local theComment=;
    if [$lang == "Java"] #Surprisingly, an error occurs here: prog.sh: line 6: [Java: command not found
    then
        echo "//"$theComment; return;
    else
        echo "Language not found!"; return;
    fi
}

getComment "Java" "Whoo!";

exit $?

I'm writing a Bash script that compares a variable to a string literal, and I'm using [$lang == "Java"](as shown above) to compare the value of langto "Java". However, this comparison produces the following error:

我正在写一个bash脚本,一个变量进行比较,以一个字符串,以及我使用[$lang == "Java"](如上所示)比较的值lang"Java"。但是,这种比较会产生以下错误:

stderr:
prog.sh: line 6: [Java: command not found

I've tried using [$lang -eq "Java"]and ($lang -eq "Java")as well, but those statements didn't work either, and they produced exactly the same error.

我也尝试过使用[$lang -eq "Java"]and ($lang -eq "Java"),但是这些语句也不起作用,并且它们产生了完全相同的错误。

Why is this error occurring, and what is the correct way to compare a local variable to a string literal?

为什么会发生此错误,将局部变量与字符串文字进行比较的正确方法是什么?

回答by Barmar

You need spaces around [and ]:

你需要周围的空间[]

    if [ "$lang" = "Java" ]

[is a command (it's a synonym for test), and like any other command you delimit the parameters with spaces.

[是一个命令(它是 的同义词test),并且像任何其他命令一样用空格分隔参数。

You should also put variables in double quotes, in case the value is empty or contains whitespace or wildcard characters.

您还应该将变量放在双引号中,以防值为空或包含空格或通配符。

Finally, the operator to perform string comparison is =, although some versions of testallow ==as an extension.

最后,执行字符串比较的运算符是=,尽管某些版本test允许==作为扩展名。

回答by Pablo Niklas

First, you have to enclose the variable between double quotes, because the variable could have some spaces or special characters.

首先,您必须用双引号将变量括起来,因为变量可能有一些空格或特殊字符。

Finally remember that "[" it's an executable by itself (usually is in /bin).

最后记住 "[" 它本身就是一个可执行文件(通常在 /bin 中)。

if [ "$lang" == "Java" ]; then

回答by Pablo Niklas

First thing is, don't use [ ] - it's betterto use [[.

首先,不要使用 [ ] -最好使用 [[.

And second - you need to add some spaces:

其次 - 您需要添加一些空格:

if [[ $lang == Java ]]