在 bash 中尝试整数相等时“找不到命令”

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

"Command not found" when attempting integer equality in bash

bash

提问by Margaret

Ok, this is probably going to be ultra obvious to anyone that has spent more time with bash than I have.

好的,对于那些在 bash 上花费的时间比我多的人来说,这可能是非常明显的。

I'm trying to run this code:

我正在尝试运行此代码:

#!/bin/bash

if ["1" -eq "2"] 
then
    echo "True"
else
    echo "False"
fi

but when I execute the file, it sends back

但是当我执行文件时,它会发回

./test.sh: line 3: 1: command not found
False

There must be something major I'm missing. I've seen people use a semicolon after the brackets, this doesn't seem to make any difference... :S

一定有什么重要的东西我错过了。我见过人们在括号后使用分号,这似乎没有任何区别......:S

采纳答案by RageZ

yep eq is used only for arithmetic comparaisons.

是的 eq 仅用于算术比较。

for string comparison you have to use =

对于字符串比较,您必须使用 =

#!/bin/bash

if [ "1" = "2" ] 
then
    echo "True"
else
    echo "False"
fi

plus you need some space around the brackets.

此外,您需要在括号周围留出一些空间。

回答by SiegeX

You need to add a space after the [and before the ]like so:

您需要在之后[和之前添加一个空格,]例如:

if [ "1" -eq "2" ]

However, that way is deprecated and the better method to use is:

但是,这种方式已被弃用,更好的使用方法是:

#!/bin/bash

if ((1 == 2)) 
then
    echo "True"
else
    echo "False"
fi

回答by Michael Burr

Try adding spaces around your brackets:

尝试在括号周围添加空格:

if [ "1" -eq "2" ]