【问题标题】:bash: for file in if exists?bash:如果文件存在?
【发布时间】:2013-04-02 21:10:18
【问题描述】:

所以,

for f in *.c; do echo "That $f is the best C code I have ever seen"; done

如果没有c文件,会很乐意打印

That *.c is the best C code I have ever seen

这是不可取的。如果没有 c 文件,是否有一种优雅的方式来修复/表达我想完全跳过循环这一事实?

【问题讨论】:

    标签: bash file loops wildcard


    【解决方案1】:

    试试:

    for f in `ls -1 *.c`; do
     echo That $f is the best C code I have ever seen
    done
    

    【讨论】:

    • 没错,这适用于*.c 不匹配任何内容的情况,但如果名称中包含带有空格的文件匹配,则可能无法按预期工作。
    • @chepner:真的吗?不知道。
    • 假设你有一个文件,foo bar.c。循环,在命令替换之后,相当于for f in foo bar.c; do:f设置为foo,然后bar.c。
    【解决方案2】:
    n=`ls -1 *.c 2> /dev/null | wc -l`
    if [ $n != 0 ]
    then
        for f in *.c; do echo "That $f is the best C code I have ever seen"; done
    fi
    

    【讨论】:

      【解决方案3】:

      设置nullglob 选项。如果没有匹配则展开为空。

      shopt -s nullglob
      for f in *.c; do …
      

      请注意,这是一个特定于 bash 的结构,它不能在普通的 sh 下工作。

      【讨论】:

        【解决方案4】:

        在 Bash 中,shopt -s nullglob 将导致不匹配任何文件的 glob 返回空扩展,而不是标识。

        对于 POSIX,可能类似于

        case *.c in '*.c' ) echo no match ;; esac
        

        有一个明显的病态例外,您可能需要单独检查是否存在一个名称为 *.c 的匹配文件。

        【讨论】:

          猜你喜欢
          • 2023-04-07
          • 2011-06-21
          • 2012-11-29
          • 1970-01-01
          • 1970-01-01
          • 2017-02-22
          • 2019-05-17
          • 1970-01-01
          • 2013-08-05
          相关资源
          最近更新 更多