Search code examples
bashsyntaxoperators

How to do exponentiation in Bash


I tried

echo 10**2

which prints 10**2. How to calculate the right result, 100?


Solution

  • You can use the let builtin:

    let var=10**2   # sets var to 100.
    echo $var       # prints 100
    

    or arithmetic expansion:

    var=$((10**2))  # sets var to 100.
    

    Arithmetic expansion has the advantage of allowing you to do shell arithmetic and then just use the expression without storing it in a variable:

    echo $((10**2)) # prints 100.
    

    For large numbers you might want to use the exponentiation operator of the external command bc as:

    bash:$ echo 2^100 | bc
    1267650600228229401496703205376
    

    If you want to store the above result in a variable you can use command substitution either via the $() syntax:

    var=$(echo 2^100 | bc)
    

    or the older backtick syntax:

    var=`echo 2^100 | bc`
    

    Note that command substitution is not the same as arithmetic expansion:

    $(( )) # arithmetic expansion
    $( )   # command substitution