02 / FILES AND STREAMS · LESSON 06

Globbing and filenames

Iterate over matching files without splitting names containing spaces.

13 min · learn at your pace

Let the shell match names

A glob such as ./logs/*.log expands to matching path arguments before the command starts. Bash does the matching, not cat or printf. Keep the wildcard outside quotes, then quote each expanded filename when using it: for file in ./logs/*.log; do ... "$file"; done.

With Bash’s default settings an unmatched pattern remains literal. Check [ -f "$file" ] || continue before acting on it. That also ignores a directory whose name happens to end in .log. shopt -s nullglob is another Bash-specific approach; it is not POSIX sh syntax.

Do not turn filenames into words

for file in $(ls logs) first creates text and then splits it. A file named night shift.log becomes two loop items. Direct globbing preserves each match as one path, including spaces and Unicode. ${file##*/} removes the longest prefix ending in a slash, leaving its basename; this expansion exists in Bash 3.2.

Use LC_ALL=C when a report needs a reproducible sort order. Locale affects sorting, character classes and matching. These exercises name that policy explicitly rather than relying on whichever locale a machine happens to use.

Try an example.sh
for file in ./logs/*.log; do
    [ -f "$file" ] || continue
    printf '%s\n' "${file##*/}"
done
YOUR TURN

Put it into practice.

Write `files.txt` containing the basenames of regular `logs/*.log` files, one per line, sorted with `LC_ALL=C`. Ignore other extensions and directories. Preserve spaces/Unicode. With no matching files, write an empty file. Replace the report on repeated runs.

See an explained solution
One way to solve it.sh
export LC_ALL=C
for file in ./logs/*.log; do
    [ -f "$file" ] || continue
    printf '%s\n' "${file##*/}"
done | sort > files.txt

The glob creates safe argument boundaries. The -f guard handles an unmatched pattern, and output redirection replaces the report.