In shell pattern matching (globbing), which wildcard matches any number of characters, including zero characters (that is, it can match an empty string)?

Difficulty: Easy

Correct Answer:

Explanation:


Introduction / Context:
Command shells like bash and zsh expand wildcard patterns before executing commands. Understanding how each wildcard behaves prevents accidental file matches and enables precise selections when scripting or working interactively on large directories of files.


Given Data / Assumptions:

  • You are using standard POSIX-style globbing (not regular expressions).
  • You want a pattern that can match an arbitrary-length sequence of characters, including none.
  • Character classes and single-character wildcards are also available.


Concept / Approach:
The asterisk '' matches any string of characters, including the empty string. The question mark '?' matches exactly one character. Bracket expressions like '[ijk]' match exactly one character chosen from the set, and '[!ijk]' matches exactly one character not in the set. Therefore, only '' satisfies the requirement of matching zero or more characters.


Step-by-Step Solution:

Match all files: ls Match all .txt files: ls .txt (matches .txt and may include 'file.txt')Match files starting with chap: ls chapDemonstrate empty match: echo XY matches 'XY' if no characters occur between


Verification / Alternative check:
Use 'printf '%s\n' ' in an empty directory and observe that shells may pass the literal '' if 'nullglob' is not set; with 'nullglob' enabled, the pattern expands to nothing. This illustrates shell options but does not change the semantic that '' can match zero characters in principle.


Why Other Options Are Wrong:

  • ? : Matches exactly one character, not zero-or-more.
  • [ijk] : Matches one character from the set i, j, or k.
  • [!ijk] : Matches one character that is not i, j, or k.
  • None of the above: Incorrect because '' is correct.


Common Pitfalls:
Confusing shell globs with regular expressions, and forgetting that some shells require options like 'nullglob' for empty expansions to vanish instead of leaving a literal asterisk.


Final Answer:
*

Discussion & Comments

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