Dave's Brain

Browse - Programming Tips - How can I make my bash glob code work nicely when there are no files

Date: 2012aug17
OS: Linux
Language: bash

Q.  How can I make my bash glob code work nicely when there are no files
that match?

A.  This code:

for I in *.jpg; do echo file=$I done
Works fine unless there are no .jpg files. In that case it executes the loop once with I set to *.jpg -- not very nice. Here's an variation that handles zero matches:
for I in $(ls *.jpg 2>/dev/null); do echo file=$I done
This works but is slightly slower since it shells out the ls command.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.