Which command pattern below would <em>not</em> correctly list exactly the files chap01, chap02, and chap04 in a Unix/Linux shell?

Difficulty: Easy

Correct Answer: ls chap[124]

Explanation:


Introduction / Context:
Shell globbing expands wildcard patterns to matching filenames. Bracket expressions like [124] select specific characters at a given position, while matches any string (including none). Understanding where and how to use these patterns is critical for selecting the intended files and avoiding accidental matches or omissions.


Given Data / Assumptions:

  • The existing files of interest are named: chap01, chap02, chap04.
  • Other similar files (for example, chap03) may exist alongside them.
  • We evaluate which pattern does not list those specific files.


Concept / Approach:
ls chap0[124] matches filenames beginning with 'chap0' and ending with 1, 2, or 4. It correctly selects chap01, chap02, and chap04. ls chap lists every name starting with 'chap', which includes the three targets (though not exclusively). In contrast, ls chap[124] looks for filenames with exactly five characters where the fifth character is 1, 2, or 4 (for example, chap1, chap2). It does not match chap01, chap02, or chap04 because those have six characters with a zero between 'chap' and the final digit. Therefore, that pattern fails to list the required files.


Step-by-Step Solution:

Check desired form: chap0X where X in {1,2,4}.Pattern that works: chap0[124] ➜ matches exactly chap01, chap02, chap04.Broad pattern: chap* ➜ includes all chap* files (superset, but still lists the three).Incorrect pattern: chap[124] ➜ matches chap1/chap2/chap4, not chap0X.


Verification / Alternative check:
Run 'printf "%s\n" chap*' in a test directory and compare expansions for each pattern. Observe that chap[124] never includes the '0' required for chap0[124].


Why Other Options Are Wrong:

  • ls chap*: Although it lists extra files, it still lists the three target files.
  • ls chap0[124]: Precisely matches the three names.
  • ls - x chap0[124]: Interpreted (typo aside) as an '-x' option with the same matching set; it still lists the targeted files on many systems.


Common Pitfalls:
Forgetting that bracket expressions match a single character, misplacing the '0', or assuming globbing uses regex rules like '?' and '+'—shell globs are simpler and differ from regular expressions.


Final Answer:
ls chap[124]

Discussion & Comments

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