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, andawk(these are typically included by default)
Step-by-Step
- 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 outputs12. You can use variables too:x=10; y=3; echo $((x * y))
outputs30. Supported operators include+,-,*,/,%(modulus), and**(exponentiation, in Bash 4.0+). - Handle division properly with integer truncation awareness
Shell arithmetic performs integer division only, discarding remainders. For example,echo $((7 / 3))returns2, not2.333.... To get the remainder, use modulus:echo $((7 % 3))returns1. If you need exact decimal results, skip to usingbcorawk. - Perform floating-point math with
bcbc(basic calculator) handles decimals and high-precision math. Start it interactively or pipe expressions into it. For example:echo "5 / 2" | bc
outputs2by default (integer mode). To enable decimals, set scale:echo "scale=2; 5 / 2" | bc
outputs2.50. You can chain operations:echo "scale=3; (10.5 + 2.3) * 1.1" | bc
returns14.080. - Use
bcinteractively for complex or repeated calculations
Typebc -lto start an interactive session with the math library loaded (enables functions likes(),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-lflag also sets default scale to 20, useful for high precision. - Calculate with
awkfor scriptable, multi-line mathawkis 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 prints20. For a single expression, just pass it as a string:awk 'BEGIN {print 100 * 0.15}'
outputs15. - Use
exprfor legacy shell compatibility (less recommended)expris older and requires spaces between operands and operators. For example:expr 5 + 7
outputs12. Note: multiplication needs escaping to avoid shell interpretation:expr 5 \* 7
outputs35. Avoidexprunless you’re writing portable POSIX shell scripts for very old systems. - 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) - 3is 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" | bcgives262144.
Common Mistakes
- Missing spaces in
expr:expr 5+7returns5+7as a string, not12. Always separate tokens with spaces. - Forgetting to escape
*in shell orexpr: 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. Usebcorawkinstead. - Not setting
scaleinbcearly enough: Ifscale=0is set globally (e.g., via.bcrc), your results may truncate unexpectedly. Always specifyscaleper 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
bcfor financial or scientific calculations where precision matters; setscalehigh (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 runavg 10 20 30to get20. - Combine pipes with
bcfor dynamic input:echo "$(ls -1 | wc -l) * 1024" | bccalculates total bytes for current directory file count. - Test your expressions with
echofirst to avoid side effects in scripts. - In Bash, use
letfor 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 tobcorawkfor floats. Verify input withecho "$var"before calculation. bcreturns unexpected truncation
Check ifscaleis set too low. For example,echo "scale=1; 10/3" | bcgives3.3, not3.33. Increasescaleor omit it for default precision (20 inbc -lmode).exprshows the expression as text
Confirm you have spaces:expr 5 + 7works,expr 5+7does 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, runsudo 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, butecho $(-5 + 3)may fail. Inbc, 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?
Useprintf: 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.