【问题标题】:Print structure of a folder with recursive function Shell script使用递归函数Shell脚本打印文件夹的结构
【发布时间】:2020-05-07 16:06:58
【问题描述】:

我想用 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=$1
    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 "$1"
fi

还有使用$1、“$1”和“${1}”有什么区别?

【问题讨论】:

  • 我的 kubuntu 没有 tree 命令。这是一个练习,所以我不知道我的导师在他们的 linux 中是否有 tree 命令

标签: bash shell sh


【解决方案1】:

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

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

dir_find .

【讨论】:

  • 谢谢。在这里使用[[]] 是什么意思?什么是缩进?
  • 这是一个更现代的[] 版本,存在于 bash 中。请参阅man bash 寻求帮助。
  • 如果$f 是一个目录,[[ -d $f ]] 返回 true。
  • 缩进的缩写是什么?
  • $indent 存储缩进空间。