【问题标题】:How to list directories and files in a Bash by script?如何通过脚本列出 Bash 中的目录和文件?
【发布时间】:2018-02-27 08:59:25
【问题描述】:

我想列出目录树,但我必须为它编写脚本,并且作为参数脚本应该采用基本目录的路径。列表应该从这个基目录开始。

输出应如下所示:

Directory: ./a
File: ./a/A
Directory: ./a/aa
File: ./a/aa/AA
Directory: ./a/ab
File: ./a/ab/AB

所以我需要为这个基目录中的每个目录和文件打印基目录的路径。

更新

运行脚本我应该在终端中输入:“.\test.sh /home/usr/Desktop/myDirectory”或“.\test.sh myDirectory” - 因为我从桌面级别运行 test.sh . 现在脚本应该从 /home/usr/Dekstop/myDirectory 级别运行”

我的 test.sh 文件中有以下命令:

find . | sed -e "s/[^-][^\/]*\//  |/g"

但它是 command,而不是 shell 代码,并像这样打印输出:

DIR: dir1
    DIR: dir2
      fileA
    DIR: dir3
    fileC
fileB

如何打印基目录中每个目录或文件的基目录路径?有人可以帮我解决吗?

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    不清楚你想要什么,

    find . -type d -printf 'Directory: %p\n' -o -type f -printf 'File: %p\n'
    

    不过看目录的子树,我觉得更有用

    find "$dirname" -type f
    

    要回答评论,也可以使用递归函数在纯 bash(没有外部命令的内置)中完成。

    rec_find() {
        local f
        for f in "$1"/*; do
            [[ -d $f ]] && echo "Directory: $f" && rec_find "$f"
            [[ -f $f ]] && echo "File: $f"
        done
    }
    
    rec_find "$1"
    

    【讨论】:

    • 命令的输出 find $1 -type d -printf 'Directory: %p\n' -o -type f -printf 'File: %p\n' 是正确的,但是你能编写脚本(shell 代码)来像上面的这个命令一样工作?
    • 是的,但是当一个较短的人可以做同样的事情时,为什么要编写更多的命令。请注意,在 $1 附近缺少引号:find "$1" .. 如果目录包含空格或某些元字符
    • 感谢您的帮助。用 bash 编写脚本是一种练习
    【解决方案2】:

    您可以使用tree 命令。键-L 表示最大深度。例子:

    tree
    .
    ├── 1
    │   └── test
    ├── 2
    │   └── test
    └── 3
        └── test
    
    3 directories, 3 files
    

    或者

    tree -L 1
    .
    ├── 1
    ├── 2
    └── 3
    
    3 directories, 0 files
    

    【讨论】:

    • 虽然tree 命令非常有用,但我看不出它如何匹配 OP 想要的输出。
    【解决方案3】:

    使用以下代码创建您的test.sh。在这里,您正在读取系统变量 $1 中的命令行参数并提供参数来查找命令。

    #!/bin/bash #in which shell you want to execute this script
    
    find $1 | sed -e "s/[^-][^\/]*\//  |/g"
    

    现在它将如何工作:-

    ./test.sh /home/usr/Dekstop/myDirectory #you execute this command
    

    这里的命令行参数将被赋值到$1。不止一个参数,您可以使用 $1 到 $9,之后您必须使用 shift 命令。 (您将在线获得更多详细信息)。

    所以你的命令现在是:-

    #!/bin/bash #in which shell you want to execute this script
    
    find /home/usr/Dekstop/myDirectory | sed -e "s/[^-][^\/]*\//  |/g"  
    

    希望这会对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 2012-06-11
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多