簡體   English   中英

使用 Bash 比較數字

[英]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 ]]; 被執行

當我改變ifelse條件的位置時:

#!/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM