在bash中,在将其作为输入后不能比较变量。

huangapple go评论59阅读模式
英文:

Cant compare variables after taking them as input in bash

问题

我有2个变量,它们是从Bash输入的,我想要打印这2个变量之间的关系,即如果X大于、小于或等于Y,以下是我尝试实现的方式:

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

我遇到了以下错误:

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

I have 2 variables which i get as input from bash, i want to print the relation between the 2 variables i.e if X is greater or less or equal to y , here is how i am trying to achieve

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

I am getting the error

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

答案1

得分: 1

以下是要翻译的代码部分:

## Edit
This looks to be a duplicate of https://stackoverflow.com/q/18668556/12957340. Here are some of the answers to that question applied to your example:

---

Try this (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
Or this (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
Or this (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

<details>
<summary>英文:</summary>

## Edit
This looks to be a duplicate of https://stackoverflow.com/q/18668556/12957340. Here are some of the answers to that question applied to your example:

---

Try this (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


Or this (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


Or this (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


</details>



huangapple
  • 本文由 发表于 2023年6月15日 15:12:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定