【问题标题】:Bash: Loop with if-statementBash:使用 if 语句循环
【发布时间】:2017-03-06 04:21:52
【问题描述】:

在我的 bash 脚本中,我对目录中的文件进行了循环,并有一个简单的 if 语句来过滤特定文件。但是,它的行为不像我预期的那样,但我不明白为什么。

(我知道我可以在 for 循环表达式 (... in "*.txt") 中过滤文件扩展名,但在我的实际情况下条件更复杂。)

这是我的代码:

#!/bin/bash
for f in "*"
do
    echo $f
    if [[ $f == *"txt" ]]
    then
        echo "yes"
    else
        echo "no"
    fi
done

我得到的输出:

1001.txt 1002.txt 1003.txt files.csv
no

我的期望:

1001.txt 
yes
1002.txt 
yes
1003.txt 
yes
files.csv 
no

【问题讨论】:

    标签: string bash loops if-statement


    【解决方案1】:

    脚本中引用错误的问题。您在 glob 的顶部有一个额外的引用,而在 echo 中缺少一个引用。

    这样吧:

    for f in *
    do
        echo "$f"
        if [[ $f == *"txt" ]]
        then
            echo "yes"
        else
            echo "no"
        fi
    done
    
    • for f in "*" 将只循环一次,f 作为文字 *
    • 未引用的echo $f 将扩展* 以输出当前目录中所有匹配的文件/目录。

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 1970-01-01
      • 2013-12-13
      • 2014-01-15
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多