Bash: Add Numbers from stdin

In Bash scripting, you can read user input from the terminal (stdin) and perform arithmetic operations on it. One common task is to accept multiple numbers as input and calculate their sum.

In this tutorial will cover different ways to read numbers from stdin and add them using Bash script, with the help of well detailed examples.


Syntax for Reading Numbers from stdin

To read numbers from stdin, you can use the read command in Bash. The read command reads input from the terminal or a file and stores it in a variable. Here’s the basic syntax:

</>
Copy
read variable_name

You can then perform arithmetic operations on the variable using $((...)) for integer addition or bc for floating-point addition.


Examples of Adding Numbers from stdin

Let’s look at different examples to understand how to read numbers from stdin and perform addition.


1. Add Two Numbers from stdin

In this example, the script prompts the user to enter two numbers and then calculates their sum using arithmetic expansion.

example.sh

</>
Copy
#!/bin/bash

# Prompt user for input
echo "Enter the first number:"
read num1

echo "Enter the second number:"
read num2

# Perform addition
sum=$((num1 + num2))

# Display the result
echo "The sum of $num1 and $num2 is $sum."

Output

Bash: Add Numbers from stdin Example

In this example, the read command captures the user input, and the addition is performed using $((...)).


2. Adding Multiple Numbers in a Loop

This example demonstrates how to sum a series of numbers entered by the user. The script uses a loop to read numbers until the user enters “done.”

example.sh

</>
Copy
#!/bin/bash

sum=0

echo "Enter numbers to add (type 'done' to finish):"

while true
do
    read input
    if [ "$input" == "done" ]; then
        break
    fi
    sum=$((sum + input))
done

echo "The total sum is $sum."

Output

Bash: Add Multiple Numbers from stdin in a Loop

In this script, the user can enter multiple numbers, and the script keeps adding them until “done” is entered. This approach is useful for summing an unknown number of inputs.


3. Adding Floating-Point Numbers from stdin Using bc

Bash does not natively support floating-point arithmetic. To add floating-point numbers, we can use the bc command-line calculator.

example.sh

</>
Copy
#!/bin/bash

echo "Enter the first floating-point number:"
read num1

echo "Enter the second floating-point number:"
read num2

# Perform addition using bc
sum=$(echo "$num1 + $num2" | bc)

echo "The sum of $num1 and $num2 is $sum."

Output

Bash: Add Numbers (floating point) from stdin

In this example, the bc command is used to handle floating-point arithmetic, providing an accurate result for the sum of the input numbers.