← Back to Bash Course | Chapter 4: Loops | Lesson 13 of 14

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:

  1. Math Functions
Syntax
bash
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

bash
#!/bin/bash
echo "2^10 = $((2 ** 10))"

sqrt_result=$(echo "sqrt(16)" | bc -l)
echo "sqrt(16) = $sqrt_result"
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
  1. Expecting Bash to provide sqrt() or sin(), when integer arithmetic has none; use bc -l.
  2. Forgetting that RANDOM gives an integer from 0 to 32767.
  3. Expecting $(( 7 / 2 )) to round, when it truncates.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.