Search code examples
bashoutputcalculatorherestring

Storing output of here-string BC calculation into a variable for error-checking


I have an assignment for school which is to create a script that can calculate a math equation any length using order of operations. I had some trouble with this and ended up finding out about here-strings. The biggest problem with the script seems to be error-checking. I tried to check the output of bc using $?, however it is 0 whether it is success or fail. In response to that I am now attempting to store the output of the here-string into a variable, and then I will use regex to check if output begins with a number. Here is the piece of code I wish to store in a variable, followed by the rest of my script.

#!/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
~

Solution

  • This should do the trick:

    #!/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
    

    Sample run:

    $ ./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
    

    Note that you might do this without a here-document like this:

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