2

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

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.