2
#!/bin/bash

sed  's/[^0-9 ]*//g'  $1 | tr " " "\n" > outfile.txt

sed '/^\s*$/d' outfile.txt > outfile1.txt


if [ $2 == "-s" ] || [ $2 == "-si" ] || [ $2 == "-is" ]
then
sum=0;
while read num;
do ((sum += num));
done < outfile1.txt;
echo "SUMA= $sum"
fi

if [ $2 == "-i" ] || [ $2 == "-si" ] || [ $2 == "-is" ]
then
ilo=1;
while read num1;
do((ilo = num1 * ilo));
echo $num1
done < outfile1.txt;
echo "ILOCZYN= $ilo"
fi

this is my script and this is 1st argument file

1 2 3 4 5 4 3 2 3 4 5 4 3 
2 2 2 2 22 3 34 4 4 5 5 5 d 
3 43 54 5 3

this is what im getting from the script when i want to get an multiply of all the numbers and sum of them

s17545@msh:~$ ./skrypt12.sh logfile.txt -si
SUMA= 241
1
.
. all of the numbers in outfile1.txt 
.
3
ILOCZYN= -2888071394797551616

any ideas what i am doing wrong?

Beforeu
  • 23

1 Answers1

2

As the page linked by @steeldriver explains, arithmetic overflow is a fact of life in Bash. You could instead:

  • use a language which supports arbitrary-size numbers out of the box such as (I believe) Haskell, Lisp or Scheme,
  • use a language which will throw an exception at arithmetic overflow, such as Java or Rust,
  • check whether the product has decreased after each operation (since all your numbers are positive), or
  • rethink your approach so that you don't need to multiply all the numbers in one go (which of course isn't always possible).
l0b0
  • 51,350
  • There's also dc e.g. sed -z 's/[^0-9][^0-9]*/*/2g' "$1" | dc -f - -ep – steeldriver Jun 02 '18 at 00:21
  • Python does bignums, and is likely already installed on more systems than the languages you name. Java does not throw for integer (primitive) overflow; it wraps-around. (For FP it uses IEEE which doesn't overflow at all but has +-Infinity values. For BigInteger, it does throw ArithmeticException or OutOfMemory, but only for humongous values.) – dave_thompson_085 Jun 02 '18 at 10:56