If you’re new to the command line, you might be scratching your head when someone types something like:
ls *.c
What does that even mean? What is ls
? What’s that little star doing? And why does it matter?
Let’s walk through step-by-step what’s happening behind the scenes—like a detective solving a mystery. 🕵️♂️🔍
🎬 Scene 1: The Shell Enters the Chat
Before anything runs, your shell (like bash
, zsh
, etc.) is the real MVP. It’s the program that reads your command and makes sense of it.
When you type:
ls *.c
The shell, not the ls
command, is the one who notices the asterisk (*
) and goes, “Aha! That’s a wildcard!”
🧠 Step-by-Step Breakdown
🪄 Step 1: Wildcard Expansion (aka Globbing)
The *
is a wildcard. It means “match anything.”
-
*.c
means: "Match all files that end in.c
"
So, if your directory has:
main.c
test.c
script.py
notes.txt
The shell will expand *.c
into:
main.c test.c
✅ Key point: The shell replaces *.c
with a list of matching filenames before it runs ls
.
🧮 Step 2: Executing the ls
Command
Now the shell runs:
ls main.c test.c
This tells the ls
command to list info about those specific files.
So the terminal might output:
main.c test.c
💡 If you want detailed info (like file sizes), you could do:
ls -l *.c
Which expands and runs:
ls -l main.c test.c
🚨 What If There Are No .c
Files?
If there are no files ending in .c
, the shell might just pass the literal *.c
to ls
, depending on your shell settings.
You’ll then see:
ls: cannot access '*.c': No such file or directory
💥 Boom. Shell said, “I couldn’t find anything, so I left it as-is.”
🛠️ Real World Examples
✅ Example 1: List all .c
files
ls *.c
Output:
main.c utils.c
✅ Example 2: Combine with other wildcards
ls *test*.c
Matches files like:
unit_test.c test_cases.c
⚠️ Example 3: Use quotes (prevents wildcard expansion!)
ls "*.c"
This is not the same. With quotes, the *
is not expanded. It looks for a file literally named *.c
.
🧠 Bonus Tip: Globbing Is Everywhere
Wildcards (*
, ?
, etc.) work with lots of commands, not just ls
:
cp *.txt backup/
rm *.log
cat data_??.csv
They’re part of shell globbing, and it’s powerful once you get used to it! 💪
🧾 TL;DR
When you type ls *.c
:
- The shell sees the
*
and expands it to match filenames. - It runs
ls
with those filenames as arguments. - You see the list of files that match
*.c
.
And that’s it! 🎉 You're officially smarter than 80% of first-year CS students. Okay, maybe 60%. 😉
Top comments (0)