bash shell脚本中的递归
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16819495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
recursion in shell script
提问by Yoland
I am learning Linux command and I am practicing and trying to write a basic shell script which list all the files and files in subfolders, like ls *, using recursion.
我正在学习 Linux 命令,我正在练习并尝试编写一个基本的 shell 脚本,它ls *使用递归列出子文件夹中的所有文件和文件,例如。
#!/bin/bash
# list-all: one command to list them all!!!!
listit () {
if [ -d "" ]
then
listit ""
else
echo ""
fi
}
ls | while read items; do
listit "$items"
done
However, the result shows:
但是,结果显示:
./list-all: line 16: 1101 Done ls
1102 Segmentation fault: 11 | while read items; do
listit "$items";
done
Is that because shell doesn't allow recursion? please help, thank you!
那是因为shell不允许递归吗?请帮忙,谢谢!
采纳答案by kojiro
The shell certainly supports recursion. But your function takes arguments, and you're passing it stdin. Besides that, you really shouldn't be parsing the output of ls. Consider this:
shell当然支持递归。但是您的函数需要参数,并且您将它传递给标准输入。除此之外,您真的不应该解析ls. 考虑一下:
listit() {
while [ "" ]; do
if [ -d "" ]; then
listit ""/*
else
printf '%s\n' ""
fi
shift
done
}
listit *
If you really want to read stdin, you'd have to rewrite listitto do that. That's tricky, since you only get one standard input, and each recursive call would try to own it. Filenames are a simple thing accessible as arguments through globbing, so I'd stick to that.
如果你真的想阅读标准输入,你必须重写listit才能做到这一点。这很棘手,因为您只能获得一个标准输入,并且每次递归调用都会尝试拥有它。文件名是一个简单的东西,可以通过通配符作为参数访问,所以我会坚持这一点。
回答by msw
You overflowed the stack with an infinite recursion. Consider calling listit /.
你用无限递归溢出了堆栈。考虑调用listit /.
The first ifwill see that /is a directory so it will call listit /which will then call listit /...
第一个if将看到这/是一个目录,因此它将调用listit /,然后调用listit /...
See this answer for what happens next.
请参阅此答案了解接下来会发生什么。

