Question

I am trying to run a comparison/search on user input in a bash script. I would like the user to be able to type in the function, the function is calculated and returned... How can I tell where in the string the group is located so I can keep things in order?

calculate 7 + 3
calculate 9.37 / 7.21
calculate 5 100 * 2.21
calculate 2783.34 – 25  

calculate -g hypotenuse 2.34 5.1   #-g argument for geometric
calculate -p 34.34/343             #-p argument for precision

calculate -g hypotenuse -p 2.34 5.1   #geometric and precision

edit: by group, I think I mean "token."

for example: things I know: ([-])([0-9])([.]*)([0-9]{1,}) defines integers or real numbers

([0-9]{1,}) defines integers

How do I retrieve the location of the token in the string, and how do I retrieve the operators?

Was it helpful?

Solution

As I said above you may use bc to perform arithmetic operations. And likely, this would be the best solution because bash itself can only do integer math.

Neverneless if you wish to get integer and fractional parts of a float number you may use the following code:

a=123.456 # an example
a_int=${a%.*}
a_fr=${a#*.}

In your example each "group" is representing as a single argument, that is:

print_args() {
    for a in "$@"; do
        echo "arg=\"$a\""
    done
}
print_args 9.37 / 7.21

will print

arg="9.37"
arg="/"
arg="7.21"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top