Tobias
Tobias

Reputation: 424

Bash: Loop with if-statement

In my bash script, I have a loop over files in a directory and a simple if-statement to filter for specific files. However, it does not behave as I expect, but I don't see why.

(I know I could filter for file extensions already in the for-loop expression (... in "*.txt"), but the condition is more complex in my actual case.)

This is my code:

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

The output I get:

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

What I would expect:

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

Upvotes: 2

Views: 2815

Answers (1)

anubhava
anubhava

Reputation: 785266

Misquoted problem in your script. You have an additional quoting at top in glob and missing a quote in echo.

Have it this way:

for f in *
do
    echo "$f"
    if [[ $f == *"txt" ]]
    then
        echo "yes"
    else
        echo "no"
    fi
done
  • for f in "*" will loop only once with f as literal *
  • Unquoted echo $f will expand * to output all the matching files/directories in the current directory.

Upvotes: 1

Related Questions