Reputation: 424
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
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 *
echo $f
will expand *
to output all the matching files/directories in the current directory.Upvotes: 1