Shell globbing: Which wildcard matches any number of characters (including zero characters) when expanding filenames in a POSIX shell?

Difficulty: Easy

Correct Answer:

Explanation:


Introduction / Context:
Filename expansion (globbing) lets you select sets of files using wildcards in the shell. Understanding how each wildcard behaves is essential for writing correct commands, avoiding accidental matches, and building robust scripts.


Given Data / Assumptions:

  • You are using a POSIX-like shell (bash, dash, ksh, zsh in sh-compatibility).
  • You want a wildcard that can match zero or more characters.
  • Hidden files do not match unless the pattern begins with a dot or dotglob is set.


Concept / Approach:
The asterisk * matches any sequence of characters, including the empty string. The question mark ? matches exactly one character. Bracket expressions like [ijk] match exactly one character from a specified set, while [!ijk] matches exactly one character not in the set. Therefore, * is the general wildcard for “zero or more characters.”


Step-by-Step Solution:

Use .txt to match all names ending with .txt (zero or more characters before .txt).Use file to match file, file1, file_backup, etc.Use * (alone) to match all non-hidden entries in the current directory.Combine with other tools: ls .log | wc -l to count logs.


Verification / Alternative check:
Run echo .txt to see which names expand. To include hidden files, use a leading dot like . or enable dotglob in Bash.


Why Other Options Are Wrong:
? matches exactly one character. [ijk] matches one character chosen from i, j, k. [!ijk] matches one character not in {i, j, k}. None of these allow zero or variable-length matching.


Common Pitfalls:
Expecting * to match dotfiles; confusing globbing with regular expressions where . and * have different meanings; forgetting quotes which can prevent expansion when desired.


Final Answer:

More Questions from Unix

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion