Ubuntu bash if lessthan else 條件回傳錯誤 [: -lt: 參數預期

Ubuntu bash if lessthan else 條件回傳錯誤 [: -lt: 參數預期

我正在執行以下腳本來了解輸入的銷售價格和成本價格是否產生利潤或損失;

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

相關內容