shell 在bash [duplicate]中将变量作为输入后无法比较变量

drnojrws  于 2023-06-24  发布在  Shell
关注(0)|答案(1)|浏览(142)

此问题已在此处有答案

Why should there be spaces around '[' and ']' in Bash?(5个答案)
How can I compare numbers in Bash?(10个答案)
8天前关闭
我有两个变量,我得到作为输入从bash,我想打印两个变量之间的关系,即如果X大于或小于或等于y,这是我试图实现的

read X
read Y

if ["$X" < "$Y"]
    then 
        echo "X is less than Y"
else 
    if ["$X" > "$Y"]
    then 
        echo "X is Greater than y"
    else 
        echo "X is equal to Y"
    fi
fi

我得到的错误

line 4: 2]: No such file or directory
line 8: [5: command not found
k4emjkb1

k4emjkb11#

编辑

这看起来是How can I compare numbers in Bash?的复制品。以下是应用于您的示例的一些问题的答案:
试试这个(POSIX):

#!/bin/sh

read X
read Y

if [ "$X" -lt "$Y" ]
    then
        echo "X is less than Y"
else
    if [ "$X" -gt "$Y" ]
    then
        echo "X is Greater than y"
    else
        echo "X is equal to Y"
    fi
fi

POSIX(POSIX):

#!/bin/sh

read X
read Y

if [ "$X" \< "$Y" ]
    then
        echo "X is less than Y"
else
    if [ "$X" \> "$Y" ]
    then
        echo "X is Greater than y"
    else
        echo "X is equal to Y"
    fi
fi

Bash(bash):

#!/bin/bash

read X
read Y

if [[ "$X" < "$Y" ]]
    then
        echo "X is less than Y"
else
    if [[ "$X" > "$Y" ]]
    then
        echo "X is Greater than y"
    else
        echo "X is equal to Y"
    fi
fi

相关问题