I thought this would be simple - but it is proving more complex than I expected.
I want to iterate through all the files of a particular type in a directory, so I write this:
#!/bin/bash for fname in *.zip ; do echo current file is ${fname} done
This works as long as there is at least one matching file in the directory. However if there are no matching files, I get this:
current file is *.zip
I then tried:
#!/bin/bash FILES=`ls *.zip` for fname in "${FILES}" ; do echo current file is ${fname} done
While the body of the loop does not execute when there are no files, I get an error from ls:
ls: *.zip: No such file or directory
How do I write a loop which cleanly handles no matching files?
shopt -s nullglob
before running the for loop.FILES=
ls *.zip; for fname in "${FILES}"...
but it does work as expected withfor fname in *.zip ; do....
for file in *.zip
, not`ls ...`
. @cuonglm's suggestion is so that*.zip
expands to nothing when the pattern doesn't match any file.ls
without arguments lists the current directory.ls
is generally to be avoided: Why not parsels
?; also see the link near the top of that page to BashGuide's ParsingLs article.