问题描述
我一直在尝试比较Bash中的两个数字是否相等(如果相等,则打印一条消息),但是对于这个简单的程序,我却收到了一些奇怪的错误消息:
I've been trying to compare whether two numbers in Bash are equal (and print a message if they are equal), but I'm getting some strange error messages for this simple program:
#!/bin/bash
fun2 (){
$x = 3
//#prog.sh: line 4: =: command not found
if [x == 3]
then
//#prog.sh: line 6: [x: command not found
echo "It's 3!"
fi
}
fun2
相应的错误显示在导致这些错误的行下方.
The corresponding errors are shown below the lines that caused those errors.
推荐答案
必须为:
if [ $x -eq 3 ]; then .....
如果您希望使用更具可读性和自我解释性的代码,请使用以下语法:
if you prefer a more readable and self-explanatory code, use this syntax:
if test $x -eq 3; then .....
说明:
要比较整数,必须使用这些运算符(从man测试复制):
To compare integers you must use those operators (copied from man test):
INTEGER1 -eq INTEGER2
INTEGER1 is equal to INTEGER2
INTEGER1 -ge INTEGER2
INTEGER1 is greater than or equal to INTEGER2
INTEGER1 -gt INTEGER2
INTEGER1 is greater than INTEGER2
INTEGER1 -le INTEGER2
INTEGER1 is less than or equal to INTEGER2
INTEGER1 -lt INTEGER2
INTEGER1 is less than INTEGER2
INTEGER1 -ne INTEGER2
INTEGER1 is not equal to INTEGER2
运算符==和!=仅用于字符串比较.
operators == and != are for string comparison only.
有关信息:"["命令是系统"test"命令的别名.
for information: "[" command is an alias for system "test" command.
这篇关于检查一个数字是否等于bash中的另一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!