bash - 递归 bash 脚本:如何在递归调用中修改函数参数
问题描述
我正在尝试使用递归算法来反转 bash 中的字符串。
func:
if string is length 1 or 0
return string
else
return concatenation of last letter + func(the other letters)
这是我的反向功能:
reverse () {
if [[ ${#1} -le 1 ]]
then
echo $1
else
tail=${1: (-1)}
length=${#1}
rest=${1:0:((length-1))}
echo "${tail}""${reverse rest}"
fi
}
我明白了,${reverse rest}: bad substitution
所以我认为我将参数传递给递归函数调用的方式存在问题。
对此有什么想法吗?感谢您的帮助。
解决方案
你需要类似的东西:
reverse(){
local arg=$1
test ${#arg} -le 1 && echo "$arg" || echo "${arg: -1}$(reverse "${arg:0:-1}")"
}
推荐阅读
- grails - 在域类中使用“布尔”变量,未创建表
- python-3.x - 如何在 python 中运行 mongodb 查询
- powershell - powershell 性能:Get-ChildItem -Include 与 Get-ChildItem | Where-对象
- javascript - jQuery函数冲突
- python-3.x - 为什么 spaCy 不像斯坦福 CoreNLP 那样在标记化过程中保留单词内连字符?
- java - 应用 google drive api quickstart 时无法创建目录 /tokens
- sumologic - 如何在 sumologic 中创建聚合表?
- php - php PDO Datatable Llist json数据列表
- hadoop - Hadoop put 和 copyfromlocal 的区别
- javascript - 如何通过 POST 将双滑块最小值和最大值发送到 PHP