简体   繁体   中英

bash: bc command's evaluation of *

I am using the bc command in UNIX to parse some math expressions. I have two small functions:

function bashcalc {
      echo $@ | bc -l
}

function2 {
      ...
      catMinusMouse=$(bashcalc "$cat_angle - $mouse_angle")
      cos=$(cosine $catMinusMouse)
      val=$(bashcalc "$cat_radius * $cos")   ##PARSE ERROR
      ...
}

When I tried to run the expression following val, I got quite a few "(standard_in) 1: parse error"s.

My first thought was that the asterisk was the issue so I tried escaping it. That however gave me an illegal character error.

The solution ended up being removing all of the whitespace

   val=$(bashcalc "$cat_radius*$cos")

QUESTION: Why did calculating catMinusMouse (with spaces around the subtraction operator) work while the same format with multiplication did not work?

you need escape the * or enclose it into "quotes"

3 variants:

#!/bin/bash

function bashcalc {
    echo "$@" | bc -l
}

function2() {
    cat_radius=0.9
    catMinusMouse=0.4

    val=$(bashcalc "$cat_radius" "*" "c($catMinusMouse)")
    echo $val

    #or
    val=$(bashcalc "$cat_radius * c($catMinusMouse)")
    echo $val

    #or
    val=$(bc -l <<EOF
$cat_radius * c($catMinusMouse)
EOF
)
    echo $val
}

function2

The real problem here is that you have not quoted $@ in your bashcalc function.

Change it to:

function bashcalc {
      echo "$@" | bc -l
}

Even better, don't use echo . Change it to:

bashcalc() {
    bc -l <<< "$@"
}

Try with the following:

val=$(echo "$cat_radius * $cos"| bc)

that is, pipe to bc (bashcalc) and it will make the calculation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM