use*_*680 3 linux bash recursion
我想弄清楚递归在bash脚本中是如何工作的.
我想插入数字作为参数:
sh script.sh 4
Run Code Online (Sandbox Code Playgroud)
结果将是(1 + 2 + 3 + 4)= 10
这就是我写的,在我脑海中工作得很好,但不能使它工作.
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
Run Code Online (Sandbox Code Playgroud)
我想我想象得对,但可能我错了.
不要使用全局变量:
#!/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)
Run Code Online (Sandbox Code Playgroud)
笔记:
local声明命名变量是此函数的本地变量(ref)sum=${2:-0}将"sum"变量定义为第二个参数,如果第二个参数为空或未设置,则定义为0(ref)$FUNCNAME当前运行的函数的名称(ref).这是递归调用,传递"n-1"和"sum + n"作为参数.