繁体   English   中英

Shell中的递归目录列表,不使用ls

[英]Recursive directory listing in shell without using ls

我正在寻找一个脚本,该脚本使用导出和读取链接而不使用ls选项来递归列出所有文件。 我已经尝试了以下代码,但是不能达到目的。 请你帮忙。

我的代码

#!/bin/bash

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

这是一个简单的递归函数,它会列出目录:

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)

安全地执行此操作需要使用-print0 ,以便名称之间用NUL分隔(文件名中不能存在的唯一字符;名称中的换行符有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM