-2

I'm trying to complete a script that will take 3 numbers from the command line and sum them, then display the output as "1 + 2 + 3 = 6". Here's the code I have:

clear
echo
for count
do
echo -n "$count + "
done
echo
echo
echo
echo All Done

I can make it output "1 + 2 + 3 +", but can't figure out how to get rid of the last plus or have the " = 6".

Trey
  • 1

2 Answers2

2

Building on a solution to one of many similar questions:

#!/bin/sh

IFS=+
printf '%s = %s\n' "$*" "$(($*))"
  • "$*" will expand to the positional parameters (the command line arguments), separated by $IFS. We set IFS to + separately.

  • "$(($*))" uses $(( ... )), which is an arithmetic substitution, to evaluate the arithmetic value of $*, the command line arguments with + in-between them.

  • printf is used to output the two strings with a = between them.

Testing:

$ ./script.sh 1 2 3
1+2+3 = 6
$ ./script.sh -1 2 3
-1+2+3 = 4
$ ./script.sh 1 2 3 4 2 2 3 1
1+2+3+4+2+2+3+1 = 18

What's missing in the script above is a validation of the supplied command line arguments to make sure they are integers. This is done for one value in the question "Checking if an input number is an integer".

Kusalananda
  • 333,661
0
#! /usr/bin/gawk -E
BEGIN {
  sum = 0
  if (ARGC > 1) {
    for (i = 1; i < ARGC; i++) {
      n = strtonum(ARGV[i])
      printf "%s", i == 1 ? n : n < 0 ? " - " (-n) : " + "n
      sep = " + "
      sum += n
    }
    print " = "sum
  }
}
  • That should accept floating point (but not inf, nan or things like 0x1p6), hexadecimal and octal numbers
  • For each argument, only the leading part (ignoring blanks) that can be interpreted as a number is considered.
  • Note that the locale is honoured for the decimal-point (. in English, , in many other languages).
  • Floating point numbers are printed as if using printf("%.6g") and integers as if using printf("%d"). Internally, gawk uses your C compiler double and long types internally, but with recent versions can be told to use arbitrary precision with the -M option and the PREC variable.
$ locale decimal_point
.
$ that-script 1.23 -1e2 0x30 010 garbage
1.23 - 100 + 48 + 8 + 0 = -42.77