Unix command line math lets you perform arithmetic directly in your terminal—ideal for quick calculations without opening a calculator app. You don’t need special tools; standard Unix shells like Bash or Zsh include built-in support via tools like expr, bc, and shell arithmetic expansion. This guide shows how to do basic and advanced math right from the command line.

What You'll Need

  • A Unix-like operating system (Linux, macOS, or WSL on Windows)
  • A working shell (Bash, Zsh, or sh—most systems come with Bash preinstalled)
  • Standard utilities: expr, bc, and awk (these are typically included by default)

Step-by-Step

  1. Use shell arithmetic expansion for simple integer math
    Shell arithmetic uses the syntax $(( expression )). For example, to add 5 and 7, type:
    echo $((5 + 7))
    This outputs 12. You can use variables too:
    x=10; y=3; echo $((x * y))
    outputs 30. Supported operators include +, -, *, /, % (modulus), and ** (exponentiation, in Bash 4.0+).
  2. Handle division properly with integer truncation awareness
    Shell arithmetic performs integer division only, discarding remainders. For example, echo $((7 / 3)) returns 2, not 2.333.... To get the remainder, use modulus: echo $((7 % 3)) returns 1. If you need exact decimal results, skip to using bc or awk.
  3. Perform floating-point math with bc
    bc (basic calculator) handles decimals and high-precision math. Start it interactively or pipe expressions into it. For example:
    echo "5 / 2" | bc
    outputs 2 by default (integer mode). To enable decimals, set scale:
    echo "scale=2; 5 / 2" | bc
    outputs 2.50. You can chain operations:
    echo "scale=3; (10.5 + 2.3) * 1.1" | bc
    returns 14.080.
  4. Use bc interactively for complex or repeated calculations
    Type bc -l to start an interactive session with the math library loaded (enables functions like s(), c(), l()). In this session, you can define variables and do multi-step math:
    scale=4
    x = 100
    y = 3.1415
    (x * y) / 2

    Press Ctrl+D to exit when done. The -l flag also sets default scale to 20, useful for high precision.
  5. Calculate with awk for scriptable, multi-line math
    awk is powerful for numeric processing, especially when combined with input. To compute the average of numbers (e.g., 10, 20, 30), use:
    echo -e "10\n20\n30" | awk '{sum += $1; count++} END {print sum/count}'
    This prints 20. For a single expression, just pass it as a string:
    awk 'BEGIN {print 100 * 0.15}'
    outputs 15.
  6. Use expr for legacy shell compatibility (less recommended)
    expr is older and requires spaces between operands and operators. For example:
    expr 5 + 7
    outputs 12. Note: multiplication needs escaping to avoid shell interpretation:
    expr 5 \* 7
    outputs 35. Avoid expr unless you’re writing portable POSIX shell scripts for very old systems.
  7. Combine with other tools for real-world tasks
    Use command substitution to embed math in other commands. For instance, to list files modified in the last 3 days (where 3 = $(date +%d) - 3 is too complex, so use a fixed offset for illustration):
    find . -mtime -$(echo "$(date +%d) - 3" | bc)
    Or convert MB to KB: echo "scale=0; 256 * 1024" | bc gives 262144.

Common Mistakes

  • Missing spaces in expr: expr 5+7 returns 5+7 as a string, not 12. Always separate tokens with spaces.
  • Forgetting to escape * in shell or expr: The shell interprets * as a wildcard. Use \* or quotes to avoid glob expansion.
  • Assuming shell math supports decimals: echo $((3.5 * 2)) throws a syntax error. Use bc or awk instead.
  • Not setting scale in bc early enough: If scale=0 is set globally (e.g., via .bcrc), your results may truncate unexpectedly. Always specify scale per calculation unless you want consistent truncation.
  • Using / for integer division when you need remainder: Use % for modulo operations to extract remainders, not division alone.

Tips

  • For quick one-liners in scripts, prefer $((...)) for integers—it’s fast and built-in.
  • Use bc for financial or scientific calculations where precision matters; set scale high (e.g., scale=10) and round manually if needed.
  • Store frequently used calculations in shell functions. Example:
    avg() { awk "BEGIN {sum=0; for(i=1;i<=NF;i++) sum+=\$i; print sum/NF}" <<< "$*"; }
    Then run avg 10 20 30 to get 20.
  • Combine pipes with bc for dynamic input: echo "$(ls -1 | wc -l) * 1024" | bc calculates total bytes for current directory file count.
  • Test your expressions with echo first to avoid side effects in scripts.
  • In Bash, use let for variable assignment: let "x = 5 + 3"; echo $x.

Troubleshooting

  • "syntax error: invalid arithmetic operator"
    Most likely, you used a non-integer in shell arithmetic (e.g., echo $((3.2 + 1))). Switch to bc or awk for floats. Verify input with echo "$var" before calculation.
  • bc returns unexpected truncation
    Check if scale is set too low. For example, echo "scale=1; 10/3" | bc gives 3.3, not 3.33. Increase scale or omit it for default precision (20 in bc -l mode).
  • expr shows the expression as text
    Confirm you have spaces: expr 5 + 7 works, expr 5+7 does not. If using in a script, ensure no quoting issues (e.g., avoid double quotes around the entire expression).
  • bc: command not found
    Install it: on Debian/Ubuntu, run sudo apt install bc; on RHEL/CentOS, sudo yum install bc; on macOS, it’s preinstalled. If missing on macOS, check Homebrew or reinstall command line tools.
  • Unexpected results with negative numbers
    Use parentheses in shell arithmetic: echo $((-5 + 3)) works, but echo $(-5 + 3) may fail. In bc, negative numbers work without parentheses: echo "-5 + 3" | bc.

Frequently Asked Questions

Can I calculate exponents like 2^10 in the shell?

Yes—Bash 4.0+ supports ** in arithmetic expansion: echo $((2 ** 10)) returns 1024. In older shells, use bc: echo "2^10" | bc.

How do I round decimal results in bc?

bc truncates, so round manually. For two decimal places, add 0.005 before truncating: echo "scale=2; (10/3) + 0.005" | bc gives 3.33.

Is there a faster way for simple addition in scripts?

Use shell arithmetic: $((a + b)) is faster than spawning external tools like bc. For large loops, this avoids process overhead.

Can I use variables from environment variables in shell math?

Yes—just reference them directly: export TOTAL=100; echo $((TOTAL * 2)) outputs 200. No need for $ inside $((...)).

Why does bc sometimes ignore my scale setting?

Scale only affects division, not multiplication or addition. For scale=2; 0.1 * 0.2, bc returns .02 (correct), but scale=2; 1/3 + 1/3 uses scale=2 for each division, then adds—resulting in .33 + .33 = .66.

How do I convert binary/hex to decimal on the command line?

Use printf: printf "%d\n" 0xFF outputs 255, or printf "%d\n" 0b1010 outputs 10 in Bash. For arbitrary bases, echo "obase=10; ibase=2; 1010" | bc returns 10.