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?
The sqrt() function returns the nonnegative square root of x.
Use the -v flag with printf to assign a shell variable to store the data instead of printing it in standard output. The output prints the stored variable contents. Note: Read our tutorial to learn everything about bash functions.
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()
.
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)}')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With