英文:
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" < "$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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论