Date: 2012aug17
Update: 2025sep15
OS: Linux
Language: bash
Q. bash: How can I make my bash glob code work nicely when there are no files
that match?
A. This code:
for FILE in *.jpg; do
echo file=$FILE
done
Works fine unless there are no .jpg files.
In that case it executes the loop once with FILE set to *.jpg -- not very nice.
Here's an variation that handles zero matches:
for FILE in $(ls *.jpg 2>/dev/null); do
echo file=$FILE
done
This works but is slightly slower since it shells out the ls command.
And its not as simple.
There is still the issue of handling spaces in filenames.