2011-12-01 45 views
0

我不明白,爲什麼在這段代碼問題使用「MUL」和「國防部」運營商在猛砸

echo "Please, give me two numbers:" 
echo 1: 
read a 
echo 2: 
read b 
echo "a = $a" 
echo "b = $b" 

OPT="Sum Sub Div Mul Mod" 
select opt in $OPT; do 

if [ $opt = "Sum" ]; then 
sum=$(echo $a + $b | bc -l) 
echo "SUM is: $sum" 

elif [ $opt = "Sub" ]; then 
sub=$(echo $a - $b | bc -l) 
echo "SUB is: $sub" 

elif [ $opt = "Div" ]; then 
    div=$(echo $a/$b | bc -l) 
    echo "DIV is: $div" 

elif [ $opt = "Mul" ]; then 
    mul=$(echo $a * $b | bc -l) 
    echo "MUL is: $mul" 

elif [ $opt = "Mod" ]; then 
    mod=$(echo $a % $b | bc -l) 
    echo "MOD is: $mod" 

else 
clear 
echo "wrong choise" 
exit 

fi 

done 

執行正確總結,SUB和DIV,但如果我想要做的MUL或MOD操作,它給我一個錯誤:

(standard_in) 1: syntax error

(standard_in) 1: illegal character: ~

(standard_in) 1: illegal character: ~

回答

1

這應該如你所願。您需要轉義*%。而你又echo "MOD is $mul"

echo "Please, give me two numbers:" 
echo 1: 
read a 
echo 2: 
read b 
echo "a = $a" 
echo "b = $b" 

OPT="Sum Sub Div Mul Mod" 
select opt in $OPT; do 

if [ $opt = "Sum" ]; then 
sum=$(echo $a + $b | bc -l) 
echo "SUM is: $sum" 

elif [ $opt = "Sub" ]; then 
sub=$(echo $a - $b | bc -l) 
echo "SUB is: $sub" 

elif [ $opt = "Div" ]; then 
    div=$(echo $a/$b | bc -l) 
    echo "DIV is: $div" 

elif [ $opt = "Mul" ]; then 
    mul=$(echo $a \* $b | bc -l) 
    echo "MUL is: $mul" 

elif [ $opt = "Mod" ]; then 
    mod=$(echo $a \% $b | bc -l) 
    echo "MOD is: $mod" 

else 
clear 
echo "wrong choice" 
exit 

fi 

done 
1

您需要引用*,否則它是由外殼擴展。

mul=$(echo $a '*' $b | bc -l) 

%應該罰款不帶引號的,但爲了簡單起見,你可以給所有的運營商。

+0

是的謝謝。 我也發現這個解決方案: mul = $(echo「$ a * $ b」| bc -l) 也適用於'%'。 – Kyrol

+1

是的,任何引用都可以,所以拿一個你喜歡的 – unbeli