Mathematical Expression Result Assigned to a Bash Variable

How to echo result of math expression AND save it to a variable in Bash

How about

wcExp=$(echo 'e(l(5)*.16)' | bc -l)
echo "$wcExp"

How to assign output of float expression to a variable in a shell script?

You need to use quotes around scale=2 and your math expression:

a=10; b=3
c=$(echo "scale=2; $a / $b" | bc)
echo "$c"

3.33

Execute a input in form of mathematical expression in bash

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

Evaluating a mathematical expression stored as a string, into a single number (bash)

How about:

python -c "print $NUM"

By the way, you could just write

BASE="1.e8*1.07**%d"

(In fact, you don't even need the quotes.)

variable error in bash when doing calculation

You received that error because you passed an invalid arithmetic expression into a bash arithetic expansion. Only an arithmetic expression is allowed for this place. What you try to do seems like this:

ref="$(grep -v ">" /data/ref/EN | wc -c)"
sample="$(grep -v ">" /example/SR | wc -l)"

# this is only integer division
#u=$(( sample / ref ))
#z=$(( 100 * u ))

# to do math calculations, you can use bc
u=$(bc <<< "scale=2; $sample/$ref")
z=$(bc <<< "scale=2; 100*$u")

printf "%d, %d, %.2f, %.2f\n" "$ref" "$sample" "$u" "$z"

so hopefully you get an output like this:

41858, 38986, 0.93, 93.00

Notes:

  • There is no need to cd before executing a grep, it accepts the full path with the target filename as an argument. So without changing directory, you can grep various locations.

  • In order to save the output of your command (which is only a number) you don't need to save it in a file and cat the file. Just use the syntax var=$( ) and var will be assigned the output of this command substitution.

  • Have in mind that / will result to 0 for the division 38986/41858 because it's the integer division. If you want to do math calculations with decimals, you can see this post for how to do them using bc.

  • To print anything, use the shell builtin printf. Here the last two numbers are formatted with 2 decimal points.



Related Topics



Leave a reply



Submit