循环遍历无法正常工作的目录中的文件

Lig*_*War 1 bash

考虑这个简单的脚本:

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

for f in "$DIR"; do
    if [[ "$f" == "*.txt" ]];
    then
        echo "Filename is $f"
fi
done
Run Code Online (Sandbox Code Playgroud)

我只想返回扩展名为.txt的文件.用以下方法调用脚本:

./script1 /home/admin/Documents
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*ech 8

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

for file in "$1"/*
Run Code Online (Sandbox Code Playgroud)

值得一提的是for,没有任何内置行为来枚举目录中的项目,它只是遍历您传递它的单词列表.的*,由外壳扩展,是在循环迭代过的文件列表什么结果.

您的情况也需要修改,因为*需要超出引号(其余部分也不需要在其中):

if [[ $f = *.txt ]]
Run Code Online (Sandbox Code Playgroud)

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

for file in "$1"/*.txt
Run Code Online (Sandbox Code Playgroud)

您可能还想考虑没有匹配的情况,在这种情况下,我猜您希望循环不运行.在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
Run Code Online (Sandbox Code Playgroud)