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. – cuonglm Oct 30 '15 at 14:07FILES=
ls .zip; for fname in "${FILES}"...
but it does work as expected with `for fname in .zip ; do....` – symcbean Oct 30 '15 at 14:12for 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. – Stéphane Chazelas Oct 30 '15 at 14:16ls
is generally to be avoided: Why not parsels
?; also see the link near the top of that page to BashGuide's ParsingLs article. – PM 2Ring Nov 01 '15 at 11:03ls
, just use a plain glob. – cuonglm Nov 02 '15 at 01:25