这里有一个简单的递归函数做一个目录列表:
list_dir() {
local i # do not use a global variable in our for loop
# ...note that 'local' is not POSIX sh, but even ash
# and dash support it.
[[ -n $1 ]] || set -- . # if no parameter is passed, default to '.'
for i in "$1"/*; do # look at directory contents
if [ -d "$i" ]; then # if our content is a directory...
list_dir "$i" # ...then recurse.
else # if our content is not a directory...
echo "Found a file: $i" # ...then list it.
fi
done
}
另外,如果通过“递归”,你刚才说你要上市要递归的,并且可以接受你的代码本身没有做任何递归:
#!/bin/bash
# ^-- we use non-POSIX features here, so shebang must not be #!/bin/sh
while IFS='' read -r -d '' filename; do
if [ -f "$filename" ]; then
echo "Found a file: $filename"
fi
done < <(find . -print0)
这样做s安全地要求使用-print0
,以便名称由NUL(唯一不能存在于文件名中的字符;名称内的换行符是有效。
请参阅http://mywiki.wooledge.org/BashPitfalls中的条目#1 – 2014-09-27 17:51:14