Wildcards and Globbing
Challenge Gallery
Quick Reference
| Pattern | Matches | Example |
|---|---|---|
* |
Zero or more characters | *.c – all C source files |
? |
Exactly one character | lab? – lab1, lab2, not lab10 |
[abc] |
One of: a, b, or c | file[12].c – file1.c, file2.c |
[a-z] |
One character in range | [A-Z]* – starts with uppercase |
[!abc] / [^abc] |
One character NOT a, b, or c | [!.]* – not dotfiles |
{a,b,c} |
Brace expansion (generates strings) | mkdir {src,bin,docs} |
{1..5} |
Sequence expansion | touch file{1..5}.txt |
Key distinction: Globs (*, ?, []) match existing files. Braces ({}) generate strings whether files exist or not.
How It Works
* and ? in Action
student@ubuntu:~/cscd240/lab1$ ls
hello.c hello.o main.c main.o utils.c utils.h README.md
student@ubuntu:~/cscd240/lab1$ ls *.c
hello.c main.c utils.c
student@ubuntu:~/cscd240/lab1$ rm *.o
student@ubuntu:~/cscd240/lab1$ ls main*
main.c
hello.c hello.o main.c main.o utils.c utils.h README.md
student@ubuntu:~/cscd240/lab1$ ls *.c
hello.c main.c utils.c
student@ubuntu:~/cscd240/lab1$ rm *.o
student@ubuntu:~/cscd240/lab1$ ls main*
main.c
student@ubuntu:~/cscd240$ ls -d lab?
lab1 lab2 lab3
# lab10 NOT matched -- ? is exactly one character
lab1 lab2 lab3
# lab10 NOT matched -- ? is exactly one character
Character Classes and Negation
# Files starting with a vowel
student@ubuntu:~/cscd240/lab1$ ls [aeiou]*
# Files NOT starting with uppercase
student@ubuntu:~/cscd240/lab1$ ls [!A-Z]*
hello.c main.c utils.c utils.h
student@ubuntu:~/cscd240/lab1$ ls [aeiou]*
# Files NOT starting with uppercase
student@ubuntu:~/cscd240/lab1$ ls [!A-Z]*
hello.c main.c utils.c utils.h
Brace Expansion
student@ubuntu:~$ mkdir -p project/{src,test,docs}
student@ubuntu:~$ ls project/
docs src test
student@ubuntu:~$ touch file{1..5}.txt
# Quick backup trick
student@ubuntu:~$ cp hello.{c,c.bak}
# Expands to: cp hello.c hello.c.bak
student@ubuntu:~$ ls project/
docs src test
student@ubuntu:~$ touch file{1..5}.txt
# Quick backup trick
student@ubuntu:~$ cp hello.{c,c.bak}
# Expands to: cp hello.c hello.c.bak
Common Pitfalls
*skips dotfiles.ls *won’t show.bashrc. Usels .*orls -a.- No match = literal string. If
*.xyzmatches nothing, bash passes the literal*.xyzto the command. You get a confusing “No such file” error, not a “no matches” warning. - The shell expands, not the command.
ls *.cactually runs something likels hello.c main.c utils.c. The command never sees the*. This means globs work with ANY command. rm *is not undoable. There is no trash can. Think before you glob withrm.- Spaces in braces break expansion.
{a, b}does not expand – no spaces after the comma.