Bash expr输出问题

时间:2016-04-29 17:32:44

标签: linux bash math

我正在实验课程中使用以下脚本:

#/bin/bash
#
# arithmeticLab
# demonstrates arithmetic, functions and simple if clauses
# three methods are used for arithmetic.
# the exercise requires only one.
# the three methods are:
# 1) let
# 2) expr
# 3) $((...))
# The user will input a letter and two numbers.
# the letter will
# be a(dd), s(ubtract), m(ultiply), d(ivide)
# to select an 
# arithmetic operation.

# Functions. must be before the main part of the script
# 
adder() {

# method 1. use let
let answer1=($fNumber + $sNumber)

# method 2. use expr
answer2="expr ${fNumber} + ${sNumber}"

# method 3. use $((...))
answer3=$(($fNumber + $sNumber))

} # end adder function
#--------------------------------

subtracter() {

# method 1. use let
let answer1=($fNumber - $sNumber)

# method 2. use expr
answer2='expr $fNumber - $sNumber'

# method 3. use $((...))
answer3=$(($fNumber - $sNumber))

} # end subtracter function

#---------------------------------------

multiplyer() {

# method 1. use let
let answer1=($fNumber * $sNumber)

# method 2. use expr
answer2='expr $fNumber * $sNumber)'

# method 3. use $((...))
answer3=$((fNumber * $sNumber))

} # end multiplyer function

#-------------------------------------

divider() {

# method 1. use let 
let answer1=($fNumber / $sNumber)

# method 2. use expr
answer2='expr $fNumber / $sNumber'

# method 3 use $((...))
answer3=$(($fNumber / $sNumber))

} # end divider function
# End of functions
# 

# Main part of the script
# check that user provided a letter and two numbers
# does not checkt o see if the user put in
# an incorrect letter 
# which wil simply display messages without an answer

if [ $# -lt 3 ]
then
    echo ""
    echo "Usage: Provide an operation (a,s,m,d) and two numbers"
    echo "Syntax: "$arithmetic.sh s 40 2" will produce output of "40 - 2.""
    echo "" 
    exit 1
fi

#-----------------

# set the input number to variables to pass to the functions
#

fNumber=$2
sNumber=$3

if [[ $1 == "a" ]]
    then
        adder
fi

if [[ $1 == "s" ]]
    then
        subtracter
fi

if [[ $1 == "m" ]]
    then 
        multiplyer
fi

if [[ $1 == "d" ]]
    then 
        divider
fi

#-------------------------------
# Present the answers for all three methdos
#

echo "Method 1 Answer is $answer1"
echo "Method 2 Answer is $answer2"
echo "Methdo 3 Answer is $answer3"

例如,这会产生Method 2 Answer is expr $fNumber - $sNumber而不是Method 2 Answer is expr 20的输出。

输入应为script.sh m 30 50 to multiply 30 by 50script.sh s 70 30,以便从70减去30.

我尝试在answer2 = expr ...行中使用双引号,单引号和{括号,但没有成功。

请帮忙。谢谢!

1 个答案:

答案 0 :(得分:0)

您正在使用双引号""。

更改您的行:

answer2="expr ${fNumber} + ${sNumber}"

要:

answer2=$(expr ${fNumber} + ${sNumber})