【问题标题】:Loop over files in a directory not working循环目录中的文件不起作用
【发布时间】:2017-10-05 08:27:44
【问题描述】:

考虑这个简单的脚本:

#!/bin/bash
DIR="$1"

for f in "$DIR"; do
    if [[ "$f" == "*.txt" ]];
    then
        echo "Filename is $f"
fi
done

我只想返回带有 .txt 扩展名的文件。调用脚本:

./script1 /home/admin/Documents

什么都不返回。没有错误,只是空白。怎么了?

【问题讨论】:

    标签: bash


    【解决方案1】:

    我假设您希望遍历您传递的目录中的所有文件。为此,您需要更改循环:

    for file in "$1"/*
    

    值得一提的是for 没有任何内置行为来枚举目录中的项目,它只是遍历您传递给它的单词列表。由 shell 扩展的 * 是导致循环遍历文件列表的原因。

    您的条件也需要修改,因为* 需要引号之外(其余的也不需要在引号内):

    if [[ $f = *.txt ]]
    

    但是你可以通过直接循环所有以.txt结尾的文件来避免对条件的需要:

    for file in "$1"/*.txt
    

    您可能还想考虑没有匹配项的情况,在这种情况下,我猜您希望循环不会运行。在 bash 中做到这一点的一种方法是:

    # failing glob expands to nothing, rather than itself
    shopt -s nullglob 
    
    for file in "$1"/*.txt
        # ...
    done
    
    # unset this behaviour if you don't want it in the rest of the script
    shopt -u nullglob
    

    【讨论】:

    • 我真的不得不在if [[ $f = *.txt ]] 上揉揉眼睛。这么多年,泪流满面。 ++
    • @James 这些年来你做了什么不同的事情?
    • 基本上关于"${f##.}" = "txt"之类的。
    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多