gpt4 book ai didi

linux - Bash expr 输出问题

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:37 26 4
gpt4 key购买 nike

我正在学习一门在实验室中有以下脚本的类(class):

#/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 来将 30 乘以 50script.sh s 70 30 来从 70 中减去 30。

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

请帮忙。谢谢!

最佳答案

您使用的是双引号“”。

更改您的线路:

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

致:

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

关于linux - Bash expr 输出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36944327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com