Hello,

How can I do it on a recursive way? (Function ''plus'' needs to call itself)

#!/bin/bash
function plus
{
	let GLOBAL=$GLOBAL+$1
}
GLOBAL=0
n=$1
for ((i=1; i<=n; i++))
do
plus $i
done
echo Answer: $GLOBAL

Any help is welcome!

Regards,
trume

.

Yes, but your code wasn't have correct function. It needs to be as most similar to mine ( SUM ).

Put

set -xv

as your second line. You can now see what is happening as it executes. A clue -

plus $i

doesn't do what you think it does.

Actaully, I need suggestions about the recursion. How to make function will call itself...

There are many shells. Which one are you using?
The normal meaning for PLUS parameters is" Return the sum of all the parameters", so the recursive way would be to

  • return PLUS (first+second) rest of the parameters
  • Or calculate (i, i+1) for i in the proper range and return PLUS pair-sums

Or something that does part of the work now and defers some of the work to a call of itself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.