Loop through all the files with a specific extension Loop through all the files with a specific extension bash bash

Loop through all the files with a specific extension


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 optionto simply ignore a failed match and not enter the body of the loop.

shopt -s nullglobfor i in *.java; do    ...done


Recursively add subfolders,

for i in `find . -name "*.java" -type f`; do    echo "$i"done


the correct answer is @chepner's

EXT=javafor i in *.${EXT}; do    ...done

however, here's a small trick to check whether a filename has a given extensions:

EXT=javafor i in *; do    if [ "${i}" != "${i%.${EXT}}" ];then        echo "I do something with the file $i"    fidone