首页 > 解决方案 > 递归 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所以我认为我将参数传递给递归函数调用的方式存在问题。

对此有什么想法吗?感谢您的帮助。

标签: bashrecursion

解决方案


你需要类似的东西:

reverse(){
    local arg=$1
    test ${#arg} -le 1 && echo "$arg" || echo "${arg: -1}$(reverse "${arg:0:-1}")"
}

推荐阅读