背景
这里的初学者试图学习一些Bash基础知识。
我的问题是我试图修改现有教科书示例以包括简单的输入验证。如果一个或多个输入不合适,则验证有效,但是当所有三个输入都适当时,我反而收到语法错误警告,然后给出答案。
代码已在结尾,但以下是我的想法。赞赏任何错误之处的纠正。 非常感谢。
想法
bc <<< "0.5 > 0"
,它们似乎按预期工作。代码
# loan-calc: script to calculate monthly loan payments
# formulae may be mathematically wrong, example copied from textbook
# reference only for bash scripting, not math
PROGNAME="${0##*/}"
usage () {
cat <<- EOF
Usage: $PROGNAME PRINCIPAL INTEREST MONTHS
Where:
PRINCIPAL is the amount of the loan.
INTEREST is the APR as a number (7% = 0.07)
MONTHS is the length of the loan's term.
EOF
}
read -p "Enter principal amount > " principal
read -p "Enter interest rate (E.g. 7.5% = 0.075) > " interest
read -p "Enter term length in months > " months
# Principal, interest rate, and months must be more than 0.
if (( "$principal <= 0" | bc )) || (( "$months <= 0" | bc )) || (( "$interest <= 0" | bc )); then
usage
exit 1
fi
result=$(bc <<- EOF
scale = 10
i = $interest / 12
p = $principal
n = $months
p * ((i * ((1 + i) ^ n)) / (((1 + i) ^ n) - 1))
EOF
)
printf "%0.2f\n" $result
答案 0 :(得分:0)
(( 1 | bc ))
不会将1传送到bc
中。在(( expression ))
内计算表达式时,|
是按位OR运算符, 不是管道 。
{(( bc ))
每次取值为1,因此您所有的条件测试都只是将数字与1进行“或”运算,不是将数字输入bc
。>
您在括号内的表达式应该是使用管道将数学字符串回显到bc
中的输出,例如(( $(echo "$variable <= 0"| bc) ))
。
这可以包装在一个命名函数中,这样if
语句就更具可读性。
notValid() {
(( $(echo "$1 <= 0" | bc) ))
}
# Principal, interest rate, and months must be more than 0.
if notValid "$principal" || notValid "$months" || notValid "$interest"; then
usage
exit 1
fi