[英]Comparing numbers using Bash
我寫了一個腳本來比較兩個數字:
#!/bin/bash
read X
read Y
if [[ $X -le $Y ]];
then
echo "X is less than Y"
elif [[ $X -ge $Y ]];
then
echo "X is greater than Y"
else
echo "X is equal to Y"
fi
由於某種原因,當X 和 Y 的值相同時,不執行else
條件。 而是if [[ $X -le $Y ]];
被執行。
當我改變if
和else
條件的位置時:
#!/bin/bash
read X
read Y
if [[ $X -eq $Y ]];
then
echo "X is equal to Y"
elif [[ $X -ge $Y ]];
then
echo "X is greater than Y"
else
echo "X is less than Y"
fi
對於這種情況,執行else
條件。 有人可以給我解釋一下為什么對一種情況執行else
條件而不對另一種情況執行嗎?
-le
和-ge
就像<=
和>=
。
-le
= 小於或等於-ge
= 大於或等於-lt
= 小於-gt
= 大於如果您切換到-lt
和-gt
,它將起作用:
if [[ $X -lt $Y ]]
then
echo "X is less than Y"
elif [[ $X -gt $Y ]]
then
echo "X is greater than Y"
else
echo "X is equal to Y"
fi
您也可以使用(( ))
進行算術運算。 它具有更自然的語法:您可以使用<
和>
,運算符周圍不需要空格,並且$
美元符號是可選的。
if ((X < Y))
then
echo "X is less than Y"
elif ((X > Y))
then
echo "X is greater than Y"
else
echo "X is equal to Y"
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.