sum - macOS


Overview

The sum command calculates the sum of values specified via standard input or arguments. It’s commonly used for performing simple addition operations and processing numeric data in scripts and pipelines.

Syntax

sum [options] [--] [numbers...]

Options/Flags

  • -h, –help: Display help and usage information.
  • -sSEP, –sum-separator=SEP: Specify a custom separator to use when parsing multiple numbers from input. Defaults to the space character.

Examples

Simple addition:

echo 10 5 2 | sum
# Output: 17

Using a custom separator:

echo "5,2,3,1" | sum -s,
# Output: 11

Complex usage:

grep -Eo '[0-9]+' file.txt | sum
# Sum all numbers extracted from file.txt

Common Issues

  • Invalid input: Ensure that the input contains valid numeric characters.

Integration

sum can be combined with other commands to perform advanced tasks:

  • Average calculation:
cat numbers.txt | sum | bc -l / $(wc -l numbers.txt)
  • expr: Evaluate arithmetic expressions.
  • bc: Arbitrarily precision calculator language.