Ha B Ha B - 3 months ago 6
Bash Question

How to use CTRL+D to end input?

I'm trying to write a short shell script that lets me input a bunch of numbers, each followed by ENTER, and then use CTRL+D to stop taking input and to print the sum of the inputted numbers.

The result I'm looking for is something like this:


sum.sh

1 [ENTER]

5 [ENTER]

8 [ENTER]

[CTRL+D]

14


I have a vague idea that I can do this using read and keycodes, but I haven't been able to figure it out.

Answer

You can use read -r VARNAME for that, e.g.:

#!/bin/bash

sum=0
while read -r n; do
    ((sum += n))
done
echo "$sum"