kontur
kontur

Reputation: 5220

Bash for loop parsed as single string

Why is my bash code:

for file in "production/features/*.fea"; do
    echo "FILE"
    echo $file
done

outputting:

FILE
production/features/italics.stylistic.fea production/features/lookups.fea production/features/uprights.fea production/features/uprights.stylistic.fea

I'd expect it to print:

FILE
production/features/italics.stylistic.fea 
FILE
production/features/lookups.fea 
FILE
production/features/uprights.fea 
FILE
production/features/uprights.stylistic.fea

This must be something super stupid, but as bash beginner I can't seem to figure out where it's going wrong.

Upvotes: 0

Views: 36

Answers (1)

0stone0
0stone0

Reputation: 43964

Inside quotes, the * will not expand to a list of files. To use such a wildcard successfully, it must be outside of quotes.

#!/bin/bash
for file in production/features/*.fea; do
    echo "FILE"
    echo "$file"

    # More information about why to use printf below
    # printf "FILE\n${file}\n"
done

Note: As @Inian suggested; you should quote the $file variable to prevent any misbehaviour caused by the filename. Read more about when to quote bash variable here.

This way, for() could be just a single printf;

printf "FILE\n${file}\n"

Use printf for portability reasons

Try it on Repl.it

Upvotes: 4

Related Questions