Math Functions
Bash's own math is like a basic calculator with only a few buttons. For fancier tricks like square roots, it calls in a bigger calculator to help.
In this page:
Syntax
result=$(( base ** exponent ))
result=$(echo "function(number)" | bc -l)
Math Functions
Bash itself has no built-in functions like square root or power beyond ** for integer exponentiation in $(( )).
For anything more advanced, scripts shell out to bc -l (which supports sqrt(), s() for sine, etc.) or awk. Knowing when to delegate to an external tool is part of writing effective Bash.
Note:
$(( 2 ** 10 )) computes integer powers directly without needing bc.Example: Math Functions
#!/bin/bash
echo "2^10 = $((2 ** 10))"
sqrt_result=$(echo "sqrt(16)" | bc -l)
echo "sqrt(16) = $sqrt_result"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting Bash to provide
sqrt()orsin(), when integer arithmetic has none; usebc -l. - Forgetting that
RANDOMgives an integer from 0 to 32767. - Expecting
$(( 7 / 2 ))to round, when it truncates.
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: