GGistDev

Globbing and Find

Expand filename patterns and search the filesystem robustly.

Globbing basics

  • * any string; ? single char; [abc] set; [a-z] range
echo src/*.js

Hidden files (dotfiles) are not matched by * unless dotglob is enabled.

Shell options affecting globs

shopt -s nullglob   # empty result instead of literal pattern when no match
shopt -s dotglob    # include dotfiles
shopt -s extglob    # extended globs like +(pattern), !(pattern)

Extended examples:

echo !(*.test).js     # all .js except *.test.js

Brace expansion (generation)

echo logs/{app,db}/{info,error}.log

Runs before globbing; creates words.

Find basics

find . -type f -name "*.log" -mtime -7 -size +1M -print

Common predicates:

  • -type f|d|l file/dir/symlink
  • -name/-iname pattern
  • -mtime/-mmin modified time
  • -size file size (e.g., +1M, -10k)
  • -maxdepth and -mindepth

Exec safely

find . -type f -name "*.tmp" -print0 | xargs -0 rm -f
# or
find . -type f -name "*.tmp" -exec rm -f {} +

Prefer -print0 with xargs -0 to handle spaces/newlines.

Pruning directories

find . -path "./node_modules" -prune -o -type f -name "*.js" -print

Skip heavy directories for speed.

Pitfalls

  • Quote patterns passed to commands (let find expand, not the shell)
  • Test with -print first to verify matches before -delete or -exec

Summary

  • Tune glob behavior with shopt; use extended globs when helpful
  • Use find predicates and -print0/-exec ... + for robust operations