$_ CLI In Depth
Learning progress 0%
Build · Streams, Redirection & Pipes

Build: A Timestamping Logger

Write stamp.sh, then check how it handles a missing file.

~30 min Intermediate 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: Write stamp.sh

Write stamp.sh so that it prefixes each line of standard input with the current time in HH:MM:SS. It also accepts an optional file name to read instead of standard input, and exits with status 1 with a message on standard error if that file cannot be read. Keep each line exact, then run it on three lines, one of which is indented:

BASH1 lines
printf 'first\n  indented\nlast\n' | bash stamp.sh > stamped.txt

The output must have three lines, and the indented line must keep its two leading spaces after the time.

Step 2: Check the missing-file path

Run the logger on a file that does not exist. Save its standard output, its standard error, and its status:

BASH2 lines
bash stamp.sh nope.txt > m.out 2> m.err
echo $? > m.status

The status should be 1, the standard output should be empty, and the error should be on standard error.

Files

  • stamp.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.

stamp.sh

BASH9 lines
#!/bin/bash
in=/dev/stdin
if [ $# -ge 1 ]; then
  [ -r "$1" ] || { echo "cannot read $1" >&2; exit 1; }
  in=$1
fi
while IFS= read -r line; do
  printf '%s %s\n' "$(date +%H:%M:%S)" "$line"
done < "$in"

walkthrough.sh

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

# Step 1: Write stamp.sh
cat > stamp.sh <<&#039;EOF&#039;
#!/bin/bash
in=/dev/stdin
if [ $# -ge 1 ]; then
  [ -r "$1" ] || { echo "cannot read $1" >&2; exit 1; }
  in=$1
fi
while IFS= read -r line; do
  printf &#039;%s %s\n&#039; "$(date +%H:%M:%S)" "$line"
done < "$in"
EOF
printf &#039;first\n  indented\nlast\n&#039; | bash stamp.sh > stamped.txt

# Step 2: Check the missing-file path
bash stamp.sh nope.txt > m.out 2> m.err
echo $? > m.status

Lessons this build uses