$_ CLI In Depth
Learning progress 0%
build text viewing editors

Build: A wc Clone in Bash

5 min read Module 3: Viewing Files & Text Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:11

The specification

Write a script named /workspace/mywc.sh. It takes exactly one argument, the name of a file. It prints four fields separated by single spaces: the number of newline characters in the file, the number of words, the number of bytes, and the file name exactly as it was given. A word is a run of characters that are not spaces, tabs, or newlines. If the number of arguments is not one, the script prints a usage line to standard error and exits with status 2.

For a file that contains the two lines "one two" and "three", the expected output is 2 3 14 sample.txt. The checker compares the output exactly, so the format matters as much as the numbers.

Count the lines and bytes with wc

Lines and bytes are the easy part, and the reference solution uses wc for both. Redirect the file into wc so the output is a bare number, and strip any padding the program adds. Using the same tool for these two counts is correct, because wc is the authority on what a newline and a byte are. Your own code is needed for the word count, which wc does too, but the point of the build is to write it yourself.

Count the words with a loop

A line-by-line loop with read is the natural way to count words in bash. The option -r stops read from interpreting backslashes, and clearing IFS keeps leading whitespace. The loop must also handle a last line that has no newline at the end, which read reports as a failure while still setting the variable. The test || [ -n "$line" ] handles that case.

To count the words on a line, split it by the shell into positional parameters and read the count of them. Unquoted expansion splits on whitespace and then applies pathname expansion, which is the risk here: a word that looks like a glob would expand to file names. Turning off globbing with set -f prevents that. Test your script on a line that contains an asterisk to confirm it counts the asterisk as one word.

Reading the file with a redirect

Use the input redirection done < "$file" after the loop, rather than piping cat into the loop. A pipe would run the loop in a subshell in many shells, and the variables would be lost after the loop ends. Keeping the redirect on the loop is the simplest correct structure. The file name is quoted, so a name with spaces works.

Checking your work

Create the sample file in the first lab step, then run the script on it. Compare the output with the expected line. If the word count is wrong, print the intermediate values and see which line disagrees with what you expect. A common mistake is to count the words of the whole file as a single line, which gives the wrong number when the last line is missing its newline.

Common mistakes to avoid

The first mistake is counting words with a for loop over the output of cat. The shell then splits on every whitespace character and expands any glob, so the count is wrong for lines that contain an asterisk, and it breaks for files with very long lines. The second mistake is forgetting the final line of a file that has no newline. The read loop in the reference handles that case, and it is the reason the test on the read status is more than a formality.

The third mistake is printing the file name with a path you did not intend. The specification asks for the name exactly as it was given, so the script must not resolve it to an absolute path. The fourth is forgetting to quote the file name in the redirect, which fails on any name with a space. Run your version on a file whose name contains a space before you consider it finished.

Reference solution

The reference solution below keeps the structure of the description. It checks the arguments, counts lines and bytes with wc, and counts words in a loop with globbing turned off. Compare it with your own version after you finish the lab, and notice the choice to capture the file name before the loop changes the positional parameters.

BASH14 lines
#!/usr/bin/env bash
# mywc.sh FILE: print lines, words, bytes, and the file name
set -eu
set -f
[ $# -eq 1 ] || { echo "usage: mywc.sh FILE" >&2; exit 2; }
file=$1
lines=$(wc -l < "$file" | tr -d ' ')
bytes=$(wc -c < "$file" | tr -d ' ')
words=0
while IFS= read -r line || [ -n "$line" ]; do
  set -- $line
  words=$((words + $#))
done < "$file"
echo "$lines $words $bytes $file"

The reference counts words with the positional parameters of a simple loop. It is short because the shell does the splitting. The price is that the loop reads the file only through the redirect, which is correct and efficient for a file of ordinary size.

Extensions to try

Add a -l option that prints only the line count, or make the script accept several files and print a total line. Each extension teaches something about argument handling. Keep the script short, and use the checker output as a guide when you change the behavior.

How wc counts lines, words and bytes

Visualizer

wc makes one pass over the bytes. A line is a newline character, a word is a run of non-blank characters, and bytes are not characters.

1 / 5
h
i
␠
t
h
e
r
e
\n
o
k
\n
lines
0
words
0
bytes
0

Twelve bytes in total. wc starts with three counters at zero and an "inside a word" flag set to false.

printf "hi there\nok\n" | wc
Terminal lab · 2 steps · real Linux in your browser

Build mywc.sh step by step

Create a sample file, then write a script that prints lines, words, bytes and the name.

01
Create the sample file
Create sample.txt with two lines, one two and three: ``bash cd /workspace printf 'one two\nthree\n' > sample.txt ``
Show hint for step 1
printf writes the text, and \n is a newline.
02
Write mywc.sh
Write /workspace/mywc.sh following the specification in the build. Use wc for lines and bytes, and a read loop with set -f for words. Run it with: bash mywc.sh sample.txt The output must be exactly: 2 3 14 sample.txt
Show hint for step 2
Count the words with set -- on each line and add the number of positional parameters.
Check yourself Question 1 of 4
Concept Check Purpose of set -f recall

What does set -f do in the reference mywc.sh?

Recap & Key Takeaways

wc is authoritative for lines and bytes, and a small loop with read can count words line by line.
The || [ -n line ] test keeps the last line when a file lacks a final newline.
set -f stops the shell from expanding words that look like globs while the loop splits them.
Redirect the file into the loop instead of piping into it, so variables survive the loop.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue