Shell globbing — change into a directory whose name starts with the letter ‘‘p’’ In a POSIX shell (bash/sh), which command correctly changes the current directory to a directory whose name begins with the letter p (for example, photos, projects), using filename expansion?

Difficulty: Easy

Correct Answer: cd p*

Explanation:


Introduction / Context:
Wildcards (globbing) let you match filenames and directory names without typing them fully. Knowing which pattern matches “names starting with p” is a basic shell skill useful for navigation and scripting.



Given Data / Assumptions:

  • We are in a POSIX shell (bash/sh) with standard pathname expansion enabled.
  • There exists exactly one target directory whose name starts with p (or you will choose one uniquely).
  • We want a pattern meaning “p followed by zero or more characters”.


Concept / Approach:

Shell globbing uses special metacharacters. The asterisk matches zero or more arbitrary characters. The question asks for a directory beginning with p, so the pattern is p. The question mark ? matches exactly one character; bracket expressions like [p] match a single literal from the set, not an entire name.



Step-by-Step Solution:

Decide the needed match: names that start with p and have anything (or nothing) after.Select the wildcard: matches zero or more trailing characters.Combine with cd: run cd p.Ensure the pattern expands to exactly one directory to avoid “too many arguments.”


Verification / Alternative check:

Use echo p* to preview matches before running cd. If multiple directories match (projects, papers), specify more letters (e.g., cd proj*).



Why Other Options Are Wrong:

  • cd p: tries to change into a directory literally named p only.
  • cd p?: matches exactly two characters long names like pa, not general “starts with p”.
  • cd [p]: matches a single character from set {p}; not a full name.
  • None of the above: incorrect because cd p* is valid.


Common Pitfalls:

Forgetting that globbing is performed by the shell before invoking cd; having multiple matches causes ambiguity; hidden directories (starting with dot) are not matched by p* unless explicitly included.


Final Answer:

cd p*

More Questions from Unix

Discussion & Comments

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