【问题标题】:Bash - How to use * operator to tell if multiple files exist?Bash - 如何使用 * 运算符来判断是否存在多个文件?
【发布时间】:2021-04-06 07:41:56
【问题描述】:

我想编写一个 bash 脚本来判断是否存在多个文件。我的尝试如下:

#!/bin/bash
FILE=*.dat

for d in $(find ~/Desktop/Results/ -maxdepth 4 -type d)
do
    echo $d
    cd $d 
    if [ -f "$FILE" ]; then
        echo "$FILE exists."
    fi

cd ~/Desktop/Results
done

我现在的问题是,* 运算符不适用于 FILE 变量。您知道如何使所有现有的 *.dat 文件都像代码中所示那样回显吗?

【问题讨论】:

  • 为什么不直接使用 find "~/Desktop/Results/$FILE" -maxdepth 4 -type d ?
  • @RamanSailopal 这不起作用,它说文件不存在......
  • 尝试查找 "~/Desktop/Results" -maxdepth 4 -type d -name "$FIL"
  • 您意识到FILE 的值在您的循环中不会改变,对吧?
  • 如果你想在目录树中列出所有扩展名为.dat的文件...... find ~/Desktop/Results -maxdepth 4 -name "*.dat"

标签: bash file search script


【解决方案1】:

可能是这样的

find ~/Desktop/Result -name '*.dat' -type f

这会将名称以.dat 结尾的所有文件写入stdou。如果您还对以.dat 结尾的目录感兴趣,请省略-type f

【讨论】:

    【解决方案2】:

    这应该可以实现您想要的:

    #!/usr/bin/env bash
    
    files="*.dat"
    
    shopt -s nullglob
    for d in $(find ~/Desktop/Results/ -maxdepth 4 -type d)
    do
        cd $d 
        glob=($files)
        if [ ${#glob[@]} != 0 ]; then
            echo $d
            echo "${glob[*]} exists."
        fi
    done
    
    cd ~/Desktop/Results
    

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 1970-01-01
      • 2012-08-18
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      相关资源
      最近更新 更多