【问题标题】:Using find command in bash script在 bash 脚本中使用 find 命令
【发布时间】:2026-01-13 13:20:03
【问题描述】:

我刚开始使用 bash 脚本,我需要对多个文件类型使用 find 命令。

list=$(find /home/user/Desktop -name '*.pdf') 

此代码适用于 pdf 类型,但我想同时搜索多个文件类型,如 .txt 或 .bmp。你知道吗?

【问题讨论】:

    标签: bash find command


    【解决方案1】:

    欢迎来到 bash。它是一种古老、黑暗而神秘的东西,具有强大的魔法能力。 :-)

    您询问的选项是find 命令,而不是bash。在命令行中,您可以man find 查看选项。

    你要找的是-o,代表“或”:

      list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"
    

    也就是说...... 不要这样做。 这样的存储可能适用于简单的文件名,但一旦您必须处理特殊字符,例如空格和换行符,所有赌注都取消了。详情请见ParsingLs

    $ touch 'one.txt' 'two three.txt' 'foo.bmp'
    $ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
    $ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
    MISSING: ./two
    MISSING: three.txt
    

    路径名扩展(通配符)提供了一种更好/更安全的方式来跟踪文件。然后你也可以使用 bash 数组:

    $ a=( *.txt *.bmp )
    $ declare -p a
    declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
    $ for file in "${a[@]}"; do ls -l "$file"; done
    -rw-r--r--  1 ghoti  staff  0 24 May 16:27 one.txt
    -rw-r--r--  1 ghoti  staff  0 24 May 16:27 two three.txt
    -rw-r--r--  1 ghoti  staff  0 24 May 16:27 foo.bmp
    

    Bash FAQ 有很多其他关于 bash 编程的优秀技巧。

    【讨论】:

      【解决方案2】:

      如果你想遍历你“找到”的东西,你应该使用这个:

      find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
          printf '%s\n' "$file"
      done
      

      来源:https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command

      【讨论】:

        【解决方案3】:

        你可以用这个:

        list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')
        

        此外,您可能还想使用-iname 而不是-name 来捕获带有“.PDF”(大写)扩展名的文件。

        【讨论】:

        • 为了处理带有空格的文件名,您需要稍后为$list 变量使用引号,如for i in "$list"; do echo $i; done。如果没有双引号,您的脚本会将每个“filename like this.jpg”视为三个文件:“filename”、“like”和“this.jpg”。