$_ CLI In Depth
Learning progress 0%
Build · Viewing Files & Text

Build: A wc Clone in Bash

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

~30 min Beginner 2 checked steps

Build it on a real Linux machine

The guided lab boots Linux in your browser. Each step runs a check script on that machine, so it passes only when your files and output are right.

What you will build

Step 1: Create the sample file

Create sample.txt with two lines, one two and three:

BASH2 lines
cd /workspace
printf 'one two\nthree\n' > sample.txt

Step 2: 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

Files

  • mywc.sh: the finished script.
  • walkthrough.sh: every step of the reference solution, in order.

How it is checked

Each step in the guided lab has a check script that runs on the lab machine after you finish. It passes only when the files and output it expects are there, so the lab cannot be completed by reading alone.

Reference files

Read these after you have tried the lab. They are the solutions the checks were verified against.

mywc.sh

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

walkthrough.sh

BASH25 lines
#!/usr/bin/env bash
# Reference solution for every step of the guided lab, in order.

# Step 1: Create the sample file
cd /workspace
printf &#039;one two\nthree\n&#039; > sample.txt

# Step 2: Write mywc.sh
cd /workspace
cat > mywc.sh <<&#039;EOF&#039;
#!/usr/bin/env bash
set -eu
set -f
[ $# -eq 1 ] || { echo "usage: mywc.sh FILE" >&2; exit 2; }
file=$1
lines=$(wc -l < "$file" | tr -d &#039; &#039;)
bytes=$(wc -c < "$file" | tr -d &#039; &#039;)
words=0
while IFS= read -r line || [ -n "$line" ]; do
  set -- $line
  words=$((words + $#))
done < "$file"
echo "$lines $words $bytes $file"
EOF
bash mywc.sh sample.txt > /dev/null

Lessons this build uses