[英]bash finding files in directories recursively
I'm studying the bash shell and lately understood i'm not getting right recursive calls involving file searching- i know find is made for this but I'm recently asked to implement a certain search this way or another. 我正在研究bash shell并且最近明白我没有得到涉及文件搜索的正确的递归调用 - 我知道找到了这个,但我最近被要求以这种方式实现某种搜索。
I wrote the next script: 我写了下一个脚本:
#!/bin/bash
function rec_search {
for file in `ls $1`; do
echo ${1}/${item}
if[[ -d $item ]]; then
rec ${1}/${item}
fi
done
}
rec $1
the script gets as argument file and looking for it recursively. 脚本获取作为参数文件并递归地查找它。 i find it a poor solution of mine. 我发现这是我的一个糟糕的解决方案。 and have a few improvement questions: 并有一些改进问题:
pwd
command for printing out absolute address (i tried so, but unsuccessfully) 我可以有效地使用pwd
命令打印出绝对地址(我试过,但没有成功) Your script currently cannot work: 您的脚本目前无法运行:
rec_search
, but then it seems you mistakenly call rec
该函数被定义为rec_search
,但是你似乎错误地调用了rec
if[[
你需要在“if”之后加一个空格if[[
There are some other serious issues with it too: 它也有一些其他严重的问题:
for file in `ls $1`
goes against the recommendation to "never parse the output of ls
", won't work for paths with spaces or other whitespace characters for file in `ls $1`
违反了“从不解析ls
的输出”的建议,对于带有空格或其他空格字符的路径不起作用 if
and for
to make it easier to read 你应该缩进if
和for
的主体以便于阅读 The script could be fixed like this: 该脚本可以像这样修复:
rec() {
for path; do
echo "$path"
if [[ -d "$path" ]]; then
rec "$path"/*
fi
done
}
But it's best to not reinvent the wheel and use the find
command instead. 但最好不要重新发明轮子并使用find
命令。
If you are using bash
4 or later (which is likely unless you running this under Mac OS X), you can use the **
operator. 如果您使用的是bash
4或更高版本(除非您在Mac OS X下运行它,否则可以使用**
运算符)。
rec () {
shopt -s globstar
for file in "$1"/**/*; do
echo "$file"
done
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.