Skip to content

Instantly share code, notes, and snippets.

@springmeyer
Created April 14, 2017 02:37
Show Gist options
  • Save springmeyer/6dd234ff89ba306a73608a6f45cb5506 to your computer and use it in GitHub Desktop.
Save springmeyer/6dd234ff89ba306a73608a6f45cb5506 to your computer and use it in GitHub Desktop.
Demo of how to glob for items in directory

create a directory with multiple files in it

mkdir this_dir
touch this_dir/one.txt
touch this_dir/one.csv

Now we can find all files in that directory called one (no matter file extension)

for filename in this_dir/one.*; do
  echo $filename
done

The above should print:

this_dir/one.csv
this_dir/one.txt

Great, but wait! There are bugs lurking....

What if the directory is empty?

rm this_dir/*

Now the above code would break oddly:

for filename in this_dir/one.*; do
  echo $filename
done

Now returns, when the directory is empty, this:

this_dir/one.*

Ack!. WTF bash! Instead of the search pattern being printed a more logical thing would be for the for loop to never run since no items are found.

We can fix the behavior by doing:

shopt -s nullglob

Now the loop will only find files if they exist.

Great, but wait! There is another gocha lurking...

DO NOT quote the search search. You need to use for filename in this_dir/one.*; do and not for filename in "this_dir/one.*"; do

Let's add back the files so we can test again:

touch this_dir/one.txt
touch this_dir/one.csv

If you unknowning quoted the search string the result would be:

this_dir/one.csv this_dir/one.txt

Which is problematic since that is one string with both filenames included. Not what we want.

Great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment