Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux bash script, recursion for adding numbers

I want to figure it out how recursion works in bash scripting.

I want to insert number as a parameter:

sh script.sh 4

And result would be (1+2+3+4)= 10

This is what I wrote and in my head works just fine, but can't make it work.

n=$1
j=1
result=0

recursion(){ 
    result=`expr $result + $j` 
    j=`expr $j + 1`

    if [ "$n" -gt 0 ]; then
        recursion      #is this how you do recursion?
        n=`expr $n - 1
    else
        echo $result 
    fi
}

recursion

I think I imagined right but probably I am wrong.

like image 880
user3127680 Avatar asked Mar 17 '14 18:03

user3127680


People also ask

Can you do recursion in bash?

Functions in Bash also support recursion (the function can call itself). For example, F() { echo $1; F hello; sleep 1; } . A recursive function is a function that calls itself: recursive functions must have an exit condition, or they will spawn until the system exhausts a resource and crashes.


1 Answers

Don't use global variables:

#!/bin/bash

add_recursively () {
    local n=$1
    local sum=${2:-0}
    if (( n == 0 )); then
        echo $sum
        return
    fi
    $FUNCNAME $((n - 1)) $((sum + n))
}

# input validation
if ! [[ $1 =~ ^[[:digit:]]+$ ]]; then
    echo "I need a non-negative integer, not $1"
    exit 1
fi

echo $(add_recursively $1)

Notes:

  • local declares the named variables to be local to this function (ref)
  • sum=${2:-0} defines the "sum" variable as the 2nd parameter, or 0 if the 2nd parameter is empty or unset (ref)
  • $FUNCNAME name of the currently running function (ref). This is the recursive call, passing "n-1" and "sum+n" as the parameters.
like image 85
glenn jackman Avatar answered Sep 21 '22 22:09

glenn jackman