Loop through all the files with a specific extension

AR89 picture AR89 · Jan 24, 2013 · Viewed 116k times · Source
for i in $(ls);do
    if [ $i = '*.java' ];then
        echo "I do something with the file $i"
    fi
done

I want to loop through each file in the current folder and check if it matches a specific extension. The code above doesn't work, do you know why?

Answer

chepner picture chepner · Jan 24, 2013

No fancy tricks needed:

for i in *.java; do
    [ -f "$i" ] || break
    ...
done

The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java. In bash (or shells supporting something similar), you can use the nullglob option to simply ignore a failed match and not enter the body of the loop.

shopt -s nullglob
for i in *.java; do
    ...
done