将here-string BC计算的输出存储到变量中以进行错误检查

时间:2017-03-13 22:36:52

标签: bash output calculator herestring

我有一个学校作业,即创建一个脚本,可以使用操作顺序计算任意长度的数学方程式。我遇到了一些麻烦,最后发现了这里的字符串。脚本的最大问题似乎是错误检查。 我尝试使用$?检查bc的输出,但无论是成功还是失败都是0。为了回应我现在尝试将here-string的输出存储到变量中,然后我将使用正则表达式来检查输出是否以数字开头。这是我希望存储在变量中的代码段,后面是我脚本的其余部分。

#!/bin/bash
set -f
#the here-string bc command I wish to store output into variable
cat << EOF | bc
scale=2
$*
EOF


read -p "Make another calculation?" response
while [ $response = "y" ];do
    read -p "Enter NUMBER OPERATOR NUMBER" calc1
cat << EOF | bc
scale=2
$calc1
EOF
read -p "Make another calculation?" response
done
~

1 个答案:

答案 0 :(得分:4)

这应该可以解决问题:

#!/bin/sh

while read -p "Make another calculation? " response; [ "$response" = y ]; do
    read -p "Enter NUMBER OPERATOR NUMBER: " calc1
    result=$(bc << EOF 2>&1
scale=2
$calc1
EOF
)
    case $result in
    ([0-9]*)
         printf '%s\n' "$calc1 = $result";;
    (*)
         printf '%s\n' "Error, exiting"; break;;
    esac
done

示例运行:

$ ./x.sh
Make another calculation? y
Enter NUMBER OPERATOR NUMBER: 5+5
5+5 = 10
Make another calculation? y
Enter NUMBER OPERATOR NUMBER: 1/0
Error, exiting

请注意,如果没有像这样的here-document,你可能会这样做:

result=$(echo "scale=2; $calc1" | bc 2>&1)