Recursion in a shell script

Source: Internet
Author: User
In shell scripts, the variables are global by default. So recursive calls require the local keyword to be used to display identity locals so that recursive calls to functions can be implemented. Wrote a recursive calculation of factorial script, found that when n=7 before the normal, and then the result is wrong. The upper limit of this number is small when the return value of the function is found, only to 255. So then a global variable was used to hold the result of each recursive.
#!/bin/bash

n=$1
ret=1

function multi ()
{
    local local_n=$1
    local local_n_sub_1=$ ($LOCAL _ N-1))

    if [$LOCAL _n_sub_1-lt 1]
    then
        ret=1
    else
        multi $LOCAL _n_sub_1
        ret= ' expr $LOCAL _n \* $RET '
    fi
}

multi $N

echo $RET


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.