Bash – How do i print square root of user input in bash

bash

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?

Best Answer

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().