189
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?

6
  • 5
    What about for i in $(ls *.java); do echo "do something with file $i"; done?
    – speakr
    Jan 24, 2013 at 15:38
  • there is no way to fix that if statement?
    – AR89
    Jan 24, 2013 at 15:54
  • 1
    You are comparing $i to the literal string "*.java"; pattern expansion is not performed here.
    – chepner
    Jan 24, 2013 at 16:06
  • To fix the if statement as you have it, use if [[ $i == *.java ]]; then .. (note the double [[]]s and unquoted *.java). Jan 24, 2013 at 18:23
  • 2
    Don't parse ls -- accept @chepner's answer Jan 24, 2013 at 21:51

7 Answers 7

301

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

Some more detail on the break-vs-continue discussion in the comments. I consider it somewhat out of scope whether you use break or continue, because what the first loop is trying to do is distinguish between two cases:

  1. *.java had no matches, and so is treated as literal text.
  2. *.java had at least one match, and that match might have included an entry named *.java.

In case #1, break is fine, because there are no other values of $i forthcoming, and break and continue would be equivalent (though I find break more explicit; you're exiting the loop, not just waiting for the loop to exit passively).

In case #2, you still have to do whatever filtering is necessary on any possible matches. As such, the choice of break or continue is less relevant than which test (-f, -d, -e, etc) you apply to $i, which IMO is the wrong way to determine if you entered the loop "incorrectly" in the first place.

That is, I don't want to be in the position of examining the value of $i at all in case #1, and in case #2 what you do with the value has more to do with your business logic for each file, rather than the logic of selecting files to process in the first place. I would prefer to leave that logic to the individual user, rather than express one choice or the other in the question.


As an aside, zsh provides a way to do this kind of filtering in the glob itself. You can match only regular files ending with .java (and disable the default behavior of treating unmatched patterns as an error, rather than as literal text) with

for f in *.java(.N); do
  ...
done

With the above, you are guaranteed that if you reach the body of the loop, then $f expands to the name of a regular file. The . makes *.java match only regular files, and the N causes a failed match to expand to nothing instead of producing an error.

There are also other such glob qualifiers for doing all sorts of filtering on filename expansions. (I like to joke that zsh's glob expansion replaces the need to use find at all.)

17
  • 6
    The simplest way is to add another pattern: for i in *.java *.cpp; do. If you have extended patterns enabled in bash with shopt -s extglob, you can write for i in *.@(java|cpp); do.
    – chepner
    May 13, 2015 at 13:37
  • 8
    It will if it actually matches any files. You need to use shopt -s nullglob so that a non-matching pattern expands to the empty sequence rather than be treated literally.
    – chepner
    Aug 1, 2015 at 23:08
  • 3
    @chepner It might be useful for non experts to have this indicated in the answer as someone may copy paste it and find it not working. A perfect example would be someone who is converting all ".jpg" files to ".png" before carrying out a crucial function
    – puk
    Jul 7, 2017 at 19:50
  • 5
    Instead of [ -f "$i" ] || break, we need [ -f "$i" ] || continue, right? May 5, 2018 at 16:36
  • 4
    @codeforester is right, continue is necessary. If there is a plain file named b.java and a directory named a.java, then the loop can be terminated by break before it reaches b.java.
    – nekketsuuu
    Jun 21, 2018 at 7:56
33

Recursively add subfolders,

for i in `find . -name "*.java" -type f`; do
    echo "$i"
done
5
  • instead of find . -name "*.java" -type f -exec echo \{\} \; to avoid misparsing of the output of find
    – umläute
    Jan 21, 2015 at 20:15
  • 1
    And if you don't, at least you should quote "$i" inside the loop.
    – tripleee
    Jun 7, 2016 at 13:52
  • 7
    This won't work if any of the files have whitespace in their name. May 5, 2018 at 16:38
  • 2
    @codeforester I had exactly that issue and I've fixed it using the method from this answer: askubuntu.com/a/343753/551184
    – fsinisi90
    Apr 27, 2020 at 17:11
  • 1
    If there is a space in the file this falls over completely. Dec 14, 2022 at 11:33
24

Loop through all files ending with: .img, .bin, .txt suffix, and print the file name:

for i in *.img *.bin *.txt;
do
  echo "$i"
done

Or in a recursive manner (find also in all subdirectories):

for i in `find . -type f -name "*.img" -o -name "*.bin" -o -name "*.txt"`;
do
  echo "$i"
done
2
  • 1
    according to man find: -o (meaning logical OR)
    – Timo
    Jun 5, 2021 at 19:49
  • 1
    I like the top solution of yours and upvoted it but I get an error if I do not have a file with that particular extension. Is there something I can do to ignore an extension if not found? Jul 18, 2021 at 12:50
14

the correct answer is @chepner's

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

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

EXT=java
for i in *; do
    if [ "${i}" != "${i%.${EXT}}" ];then
        echo "I do something with the file $i"
    fi
done
1
  • how would it be with a variable ext instead of .java?
    – AR89
    Jan 24, 2013 at 18:14
3

as @chepner says in his comment you are comparing $i to a fixed string.

To expand and rectify the situation you should use [[ ]] with the regex operator =~

eg:

for i in $(ls);do
    if [[ $i =~ .*\.java$ ]];then
        echo "I want to do something with the file $i"
    fi
done

the regex to the right of =~ is tested against the value of the left hand operator and should not be quoted, ( quoted will not error but will compare against a fixed string and so will most likely fail"

but @chepner 's answer above using glob is a much more efficient mechanism.

3
  • how would it be with a variable ext instead of .java?
    – AR89
    Jan 24, 2013 at 18:09
  • 2
    ack, no need for a regular expression: if [[ $i == *.java ]] or if [[ $i == *.$ext ]]. But don't parse ls Jan 24, 2013 at 21:53
  • a beautiful solution, since I could do the search in subdirectories by simply using for i in $(ls -lR); do ..., or if you want the relative path of the file : for i in $(find -L .);do ... with the help of another good answer: stackoverflow.com/a/105249/6045793 Nov 2, 2020 at 8:43
3

I agree withe the other answers regarding the correct way to loop through the files. However the OP asked:

The code above doesn't work, do you know why?

Yes!

An excellent article What is the difference between test, [ and [[ ?] explains in detail that among other differences, you cannot use expression matching or pattern matching within the test command (which is shorthand for [ )


Feature            new test [[    old test [           Example

Pattern matching    = (or ==)    (not available)    [[ $name = a* ]] || echo "name does not start with an 'a': $name"

Regular Expression     =~        (not available)    [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!"
matching

So this is the reason your script fails. If the OP is interested in an answer with the [[ syntax (which has the disadvantage of not being supported on as many platforms as the [ command), I would be happy to edit my answer to include it.

EDIT: Any protips for how to format the data in the answer as a table would be helpful!

3

I found this solution to be quite handy. It uses the -or option in find:

find . -name \*.tex -or -name "*.png" -or -name "*.pdf"

It will find the files with extension tex, png, and pdf.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.