我正在学习 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 不允许递归吗?请帮忙,谢谢!
最佳答案
shell当然支持递归。但是您的函数接受参数,并且您将其传递给标准输入。除此之外,你真的不应该parsing the output of ls
.考虑一下:
listit() {
while [ "$1" ]; do
if [ -d "$1" ]; then
listit "$1"/*
else
printf '%s\n' "$1"
fi
shift
done
}
listit *
如果您真的想读取标准输入,则必须重写 listit
才能做到这一点。这很棘手,因为您只能获得一个标准输入,并且每次递归调用都会尝试拥有它。文件名是一个简单的东西,可以通过 globbing 作为参数访问,所以我会坚持这一点。
关于linux - shell脚本中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16819495/