Difficulty: Medium
Correct Answer: ls -l | wc -l
Explanation:
Introduction / Context:
Combining simple commands with pipes is a hallmark of UNIX philosophy. To count files in a directory, you can list them with ls and then count the resulting lines with wc. Choosing the right flags ensures the count matches expectations.
Given Data / Assumptions:
Concept / Approach:
“ls -l” produces a long listing with one line per entry (plus a “total …” header in many implementations). Piping to “wc -l” counts lines, providing the number of entries. While “ls -1 | wc -l” avoids the header and is often preferred, it is not among the provided options; the classic teaching example is “ls -l | wc -l”. Be aware the “total” header line may be included depending on locale/system, but in many scenarios instructors accept this pipeline as the canonical answer.
Step-by-Step Solution:
Verification / Alternative check:
Use “ls -1 | wc -l” to avoid header line; compare counts. For hidden files include “ls -A” or “ls -a”.
Why Other Options Are Wrong:
ls | wc: counts lines, words, and bytes; not a single number unless flags are added. ls | wc -w: counts words, not entries. ls | ws -c: “ws” is not wc, and -c on wc counts bytes, not lines. None: incorrect because option B is the accepted pipeline here.
Common Pitfalls:
Forgetting hidden files (-a/-A); misinterpreting the “total” header; using aliases that change ls formatting.
Final Answer:
ls -l | wc -l
Discussion & Comments