2017-04-03 78 views
1

我要求用戶輸入2個數字和s作爲總和,或者「p」表示產品。 當我運行該腳本,我沒有看到任何結果 這裏是我的腳本根據輸入計算總和或產品

#!/bin/bash 

read -p "please enter two integers, s or p to calculate sum or product of this numbers: " num1 num2 result 
if [ result == "s" ] 
then 
echo "num1+num2" | bc 

elif [ result == "p" ] 
then 
echo $((num1*num2)) 

fi 

回答

1

爲了補充chepner's helpful answer,這解釋了在問題的代碼中的問題以及與由DRY[1] 啓發的溶液:

# Prompt the user. 
prompt='please enter two integers, s or p to calculate sum or product of this numbers: ' 
read -p "$prompt" num1 num2 opChar 

# Map the operator char. onto an operator symbol. 
# In Bash v4+, consider using an associative array for this mapping. 
case $opChar in 
    'p') 
    opSymbol='*' 
    ;; 
    's') 
    opSymbol='+' 
    ;; 
    *) 
    echo "Unknown operator char: $opChar" >&2; exit 1 
    ;; 
esac 

# Perform the calculation. 
# Note how the variable containing the *operator* symbol 
# *must* be $-prefixed - unlike the *operand* variables. 
echo $((num1 $opSymbol num2)) 

[1]除了read-p選項,該解決方案符合POSIX標準;但是,它也可以在dash中工作,它主要是一個POSIX-features-only外殼。

+1

真棒,謝謝! – Ana

3

你是比較字符串result,變量result的不是值。

if [ "$result" = s ]; then 
    echo "$(($num1 + $num2))" 
elif [ "$result" = p ]; then 
    echo "$(($num1 * $num2))" 
fi 

裏面$((...)),你可以忽略開頭的$因爲字符串被假定爲被取消引用變量名。

如果您打算將輸入限制爲整數,沒有理由使用bc

+0

謝謝!現在它的作品 – Ana