2014-09-27 73 views
0

我正在寻找一个脚本,递归地使用导出和读取链接列出所有文件,并且不使用ls选项。我尝试了下面的代码,但它没有达到目的。请你帮忙。在不使用ls的情况下在shell中递归的目录列表

我的代码 -

#!/bin/bash 

for i in `find . -print|cut -d"/" -f2` 
do 
if [ -d $i ] 
then 
echo "Hello" 
else 
cd $i 
echo * 
fi 
done 
+0

请参阅http://mywiki.wooledge.org/BashPitfalls中的条目#1 – 2014-09-27 17:51:14

回答

2

这里有一个简单的递归函数做一个目录列表:

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(唯一不能存在于文件名中的字符;名称内的换行符是有效。

相关问题