[英]Comparing numbers in bash scripting
我編寫此腳本的目的是比較bash中的2個數字,但對於某些數字卻給出了錯誤的答案。 就像我給它2&2作為輸入一樣,它給我“ X大於Y”
#!/bin/bash
read num1
read num2
if [ $num1 > $num2 ]
then
echo "X is greater than Y"
elif [ $num1 < $num2 ]
then
echo "X is less than Y"
elif [ $num1 = $num2 ]
then
echo "X is equal to Y"
fi
您可以嘗試使用bash算術上下文:
#!/bin/bash
read num1
read num2
if (( num1 > num2 ))
then
echo "X is greater than Y"
elif (( num1 < num2 ))
then
echo "X is less than Y"
elif (( num1 == num2 ))
then
echo "X is equal to Y"
fi
這對我有用:
cmp() {
num1="$1"
num2="$2"
if [ $num1 -gt $num2 ]
then
echo "X is greater than Y"
elif [ $num1 -lt $num2 ]
then
echo "X is less than Y"
elif [ $num1 -eq $num2 ]
then
echo "X is equal to Y"
fi
}
然后查看結果:
cmp 2 3
X is less than Y
cmp 2 2
X is equal to Y
cmp 2 1
X is greater than Y
由於您使用的是bash
,因此建議您使用[[ ... ]]
而不是[ ... ]
方括號。
#!/bin/sh
echo hi enter first number
read num1
echo hi again enter second number
read num2
if [ "$num1" -gt "$num2" ]
then
echo $num1 is greater than $num2
elif [ "$num2" -gt "$num1" ]
then
echo $num2 is greater than $num1
else
echo $num1 is equal to $num2
fi
(請注意:我們將-gt運算符用於>,-lt表示<,==表示=)
要進行盡可能少的更改,請使用雙括號-進入'double bracket'
模式(僅在bash / zsh中有效,在Bourne shell中無效)。
如果要與sh兼容,則可以保持'single bracket'
模式,但需要替換所有運算符。
在'single bracket'
模式下,像'<','>', '='
類'<','>', '='
運算符僅用於比較字符串。 要在'single bracket'
模式下比較數字,您需要使用'-gt'
, '-lt'
, '-eq'
#!/bin/bash
read num1
read num2
if [[ $num1 > $num2 ]]
then
echo "X is greater than Y"
elif [[ $num1 < $num2 ]]
then
echo "X is less than Y"
elif [[ $num1 = $num2 ]]
then
echo "X is equal to Y"
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.