linuxbash

Execute a input in form of mathematical expression in bash


If a user gives the following input in bash. How can I evaluate it using bash?

5+50*3/20 + (19*2)/7

I store it in a variable x. I can't figure out how to proceed.


Solution

  • You can create a simple script for that, let's call test.sh:

    #!/bin/bash
    x=$1
    echo $(($x))
    

    You can replace the line echo $(($x)) with perl -e "print $x" to get floating point output.

    And execute it with your input:

    $ test.sh "5+50*3/20 + (19*2)/7"
    17
    

    With floating point:

    #!/bin/bash
    x=$1
    var=$(perl -e "print $x")
    echo $var
    

    The results:

    $ test.sh "5+50*3/20 + (19*2)/7"
    17.9285714285714
    
    $ test.sh "-105+50*3/20 + (19^2)/7"
    -95.0714285714286