help
help

Reputation: 21

How to add an unknown amount of numbers from user input in Linux shell script

I'm trying to add up all numbers inputted by a user, however there is no limit on how many numbers a user can input for the addition. How do I code this in linux shell script?

I have this so far:

firstNumber=0
secondNumber=0
number=0


echo Please enter two numbers to add up

read firstNumber
read secondNumber

echo Would you like to keep adding numbers? YES OR NO
read answer

if answer = YES
then
echo Please add another number
read number
echo $(($firstNumber +$secondNumber + $number))
fi

while answer = NO
do
echo $(($firstNumber + $secondNumber))
done

Upvotes: 1

Views: 1233

Answers (2)

Dmitry Zaitsev
Dmitry Zaitsev

Reputation: 1

Having a list of students, one student in a line, you can add/delete them (including home directories). There can be many words in a line, though I treat the first word as a name and the last word as a surname. I use their concatenation as a username and their reverse order concatenation as a default password. If you export a file from Windows, please be sure you corrected ends of lines with dos2linux. Just run:

sudo ./add-usr-script stud-list.txt

# creates (deletes) users on a list ($1) 
# using the first (n) and the last (s) word of each line

cat $1 | while read line 
do
  echo $line
  s=${line##* }
  n=${line%% *}
  pw="${s}${n}"
  un="${n}${s}"
  pass=$(perl -e 'print crypt($ARGV[0], "password")' $pw)
  useradd -m -p "$pass" "$un"  
# userdel "$un"
# rm -r "/home/${un}"
  echo user: "$un" passwd: "$pw" encrypted_passwd: "$pass"
done

Upvotes: 0

Léa Gris
Léa Gris

Reputation: 19555

as @dash-o recommended, a simple entry sequence ended with ENTER is the most simple approach:

#!/usr/bin/env sh

sum=0

echo "Please enter integer numbers to add, or just RETURN to end."

while read -r number && [ -n "$number" ]; do
  if [ "$number" -eq "$number" ] 2>/dev/null; then
    sum=$((sum + number))
    echo "Sum is: $sum"
  else
    echo "$number is not a valid integer. Try again..." >&2
  fi
done

Or to allow multiple integers entry per line:

#!/usr/bin/env sh

# Save the shell's options state
shelloptions="$(set +o)"
# Disable globbing to prevent filename expansion in parameters
set -o noglob

sum=0

echo "Please enter integer numbers to add, or RETURN to end."

# Read lines until empty REPLY
while read -r && [ -n "$REPLY" ]; do

  # Split $REPLY as parameters
  # Globbing is turned-off so filenames will not mess with entries
  # shellcheck disable=SC2086 # Explicitly intended word splitting
  set -- $REPLY

  # Iterate numbers from the parameters array
  for number in "$@"; do

    # If $number is a valid integer
    if [ "$number" -eq "$number" ] 2>/dev/null; then
      sum=$((sum + number))
    else
      echo "$number is not a valid integer." >&2
    fi
  done
  echo "Sum is: $sum"
done

# Restore the shell's options state
eval "$shelloptions"

Upvotes: 3

Related Questions