![Ubuntu bash if lessthan else 條件回傳錯誤 [: -lt: 參數預期](https://rvso.com/image/1083729/Ubuntu%20bash%20if%20lessthan%20else%20%E6%A2%9D%E4%BB%B6%E5%9B%9E%E5%82%B3%E9%8C%AF%E8%AA%A4%20%5B%3A%20-lt%3A%20%E5%8F%83%E6%95%B8%E9%A0%90%E6%9C%9F.png)
我正在執行以下腳本來了解輸入的銷售價格和成本價格是否產生利潤或損失;
echo enter selling price
read sprice
echo enter costprice
read cprice
if [ $sprice -lt $cp ]
then
echo Loss
else
echo Profit
fi
它始終返回Profit
,並帶有錯誤代碼,例如;
:~/shell$ sh shellb.sh
enter selling price
10
enter costprice
20
shellb.sh: 6: [: -lt: argument expected
Profit
可能是什麼原因,我該如何解決這個問題?
答案1
將變數變更$cp
為$cprice
您在 行中讀到的內容read cprice
。
echo enter selling price
read sprice
echo enter costprice
read cprice
if [ $sprice -lt $cprice ]
then
echo Loss
else
echo Profit
fi
$sprice
即使與具有相同的值,腳本也會傳回 Profit $cprice
,因此為了準確起見,請將這些行新增到您的腳本中:
elif [ $sprice -eq $cprice ]
then
echo Break\ even
所以你最終得到的是:
echo enter selling price
read sprice
echo enter costprice
read cprice
if [ $sprice -lt $cprice ]
then
echo Loss
elif [ $sprice -eq $cprice ]
then
echo Break\ even
else
echo Profit
fi