4

I have recently discovered 'bc' in bash, and i have been trying to use it to print out the square root of a user input. The program i wrote below runs successfully, but it only prints out '0' and not the square root of the user input.

Here is the code i wrote:

 #!/data/data/com.termux/files/usr/bin/bash

 echo "input value below"
 read VAR
 echo "square root of $VAR is..."

 echo $((a))                                  
 a=$(bc <<< "scale=0; sqrt(($VAR))")

What is the problem with my code? What am i missing?

SLePort
  • 15,211
  • 3
  • 34
  • 44
Zero-1729
  • 78
  • 1
  • 2
  • 7

4 Answers4

8

Your bc command and the use of command substitution is correct, the problem is you have provided the echo $a earlier, when it was unset. Do:

a=$(bc <<< "scale=0; sqrt($VAR)")
echo "$a"

Also while expanding variables, you should use the usual notation for variable expansion which is $var or ${var}. I have also removed a pair of redundant () from sqrt().

heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Also, `read -p "input value below" var` ie `VAR->var`. Use of full uppercase variables in shell-script is discouraged. – sjsam Sep 05 '16 at 20:39
  • As the user input should not be trusted. You need to check if it is a number before passing it to `bc`. You may use `if [ "$var" -eq "$var" ] 2>/dev/null;then a=$(bc <<< "scale=0; sqrt($var)") else echo "$var not number"; fi`, a concept I've borrowed from [\[ here \]](http://stackoverflow.com/a/808740/1620779). – sjsam Sep 05 '16 at 21:05
2

Given that you have a number in variable var and you want square root of that variable. You can also use awk:

a=$(awk -v x=$var 'BEGIN{print sqrt(x)}')

or

a=$(echo "$var" | awk '{print sqrt($1)}')
arenaq
  • 2,304
  • 2
  • 24
  • 31
2

Using awk is also possible. For instance, the following example shows 30 decimals of the square root of 98:

awk "BEGIN {printf \"%.30f\n\", sqrt(98)}"

The command above will output 9.899494936611665352188538236078, which you can then store into the a variable.

SRG
  • 498
  • 7
  • 19
0

If you have the qalc program installed (apt-get install qalc) then you can do squareroot and other calculations more easily (in my opinion) than by using bc.

Square root can be done like this:

qalc "sqrt(36)"

The man page isn't very helpful (for my installed version at least) but you can get more info here:

alec
  • 345
  • 3
  • 14