shell脚本中的递归

时间:2013-05-29 16:38:35

标签: linux bash shell recursion

我正在学习Linux命令,我正在练习并尝试编写一个基本的shell脚本,该脚本使用递归列出子文件夹中的所有文件和文件,如ls *

#!/bin/bash

# list-all: one command to list them all!!!!

listit () {
        if [ -d "$1" ]
        then
                listit "$1"
        else
                echo "$1"
        fi  
}

ls | while read items; do
        listit "$items"
done

然而,结果显示:

./list-all: line 16:  1101 Done                    ls
      1102 Segmentation fault: 11  | while read items; do
    listit "$items";
done

那是因为shell不允许递归吗?请帮忙,谢谢!

2 个答案:

答案 0 :(得分:2)

shell肯定支持递归。但是你的函数需要参数,而你传递的是stdin。除此之外,你真的不应该是parsing the output of ls。考虑一下:

listit() {
    while [ "$1" ]; do
        if [ -d "$1" ]; then
            listit "$1"/*
        else
            printf '%s\n' "$1"
        fi
        shift
    done
}

listit *

如果你真的想读stdin,你必须重写listit来做到这一点。这很棘手,因为你只得到一个标准输入,每个递归调用都会尝试拥有它。文件名是一个简单的东西,通过globbing可以作为参数访问,所以我坚持这一点。

答案 1 :(得分:2)

您通过无限递归溢出堆栈。考虑致电listit /

第一个if会看到/是一个目录,因此它会调用listit /,然后调用listit / ...

请参阅this answer for what happens next