具有递归函数 Shell 脚本的文件夹的打印结构

Print structure of a folder with recursive function Shell script

我想用 shell 脚本打印文件夹的结构。所以它看起来像这样

File : linux -3.14/COPYING
File : linux -3.14/CREDITS
   Directory : linux -3.14/Documentation
      File : linux -3.14/Documentation/00 - INDEX
      Directory : linux -3.14/Documentation/ABI
         File : linux -3.14/Documentation/ABI/README

这是我的脚本。问题是它打印出当前目录的所有文件和文件夹,但不会打印子文件夹。也许我递归错了

dirPrint() {
    # Find all files and print them first
    file=
    for f in $(ls ${file}); do
        if [ -f ${f} ]; 
            then
                path="$(pwd)/$f"
                echo "File: $path"
        fi
    done

    # Find all directories and print them
    for f in $(ls ${file}); do
        if [ -d ${f} ];
            then
                path="$(pwd)/$f"
                echo "Directory: $path"
                echo "  $(dirPrint "$path")"
        fi
    done
}
if [ $# -eq 0 ]; then
    dirPrint .
else
    dirPrint ""
fi

以及使用 $1、"$1" 和 "${1}" 有什么区别?

您的脚本中存在各种问题。您不应该解析 ls 的输出,而是迭代通配符的扩展。始终对变量加双引号以防止文件名中的空格破坏您的命令。

#! /bin/bash
dir_find () {
    local dir=
    local indent=
    for f in "$dir"/* ; do
        printf '%s%s\n' "$indent${f##*/}"
        if [[ -d $f ]] ; then
            dir_find "$f" "    $indent"
        fi
    done
}

dir_find .