在bash递归函数 [英] Recursive function in bash
本文介绍了在bash递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做的事情,这将在bash返回一个数的阶乘函数
下面是目前的code不起作用,谁能告诉我什么是错的,如何纠正呢?我刚开始学习bash和我不知道这么多。
#!/ bash的/ bin中
阶乘()
{
令n = $ 1
如果(($ N&下; =1))
然后返回1
其他
阶乘N-1
返回$ N * $?
科幻
返回0
}
阶乘5
回声阶乘5 = $?
解决方案
有几个语法和一个相当明显的逻辑一(返回0)
一个工作版本如下:
#!/斌/庆典阶乘()
{
如果[$ 1 -le 1]
然后
返回1
其他
阶乘$ [$ 1-1]
返回$ [$ 1 * $?]
科幻
}
阶乘5
回声阶乘5 = $?
您缺少:
-
如果语法不好
-
递归调用是坏
-
收益是坏的(EVAL语法利空出现)
-
shbang线(是/斌/ bash的不是/ bash的/ bin中)
I want to do a function that will return the factorial of a number in bash
Here's the current code that doesn't work, can anyone tell me what's wrong and how to correct it? I just started learning bash and I don't know that much.
#!/bash/bin
factorial()
{
let n=$1
if (( "$n" <= "1" ))
then return 1
else
factorial n-1
return $n*$?
fi
return 0
}
factorial 5
echo "factorial 5 = $?"
解决方案
There are several syntax and a quite obvious logic one (return 0)
A working version is below:
#!/bin/bash
factorial()
{
if [ $1 -le 1 ]
then
return 1
else
factorial $[$1-1]
return $[$1*$?]
fi
}
factorial 5
echo "factorial 5 = $?"
You are missing:
if syntax is bad
Recursive call is bad
return is bad (eval syntax bad there)
shbang line (is /bin/bash not /bash/bin)
这篇关于在bash递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文