Chapter 4: Linux Advanced Commands
Practice Questions and Lab Exercises
Use a local Bash practice environment or an authorized Linux training instance. Predict the result before running each command and compare the actual output.
स्थानिक Bash environment किंवा मंजूर Linux lab वापरा. प्रत्येक command चालवण्यापूर्वी अपेक्षित result लिहा आणि प्रत्यक्ष output तपासा.
स्थानीय Bash environment या स्वीकृत Linux lab इस्तेमाल करें। हर command चलाने से पहले अपेक्षित result लिखें और वास्तविक output जाँचें।
- Count status 404 in the documented third field of the workshop fixture. Explain why counting every line containing those digits gives a different answer.
- List current workshop configuration files within the approved practice tree while excluding its archive directory.
- Project the recorded address and exact response status from the known input fields.
- Explain truncation, append, descriptor duplication and pipelines using the output each operation actually produces.
- Compare
systemctlrestart, application reload, runtime start and unit enablement on paper using a systemd service. - Identify the listening local address, protocol and port. Describe the tests needed to confirm a public site's actual response.
- Write a sample weekly schedule for 23:00 on Sunday and state the scheduler timezone. Review the expected personal crontab command without installing it.
- Build a compressed archive of the two reviewed handover files. Trace the stored paths, restore into a new directory and compare expected contents.
- Preview the client alias without connecting. Explain what would establish trusted SSH access and a verified transfer to an approved receiver.
Quick Revision
- Use
grepfor matching text,findfor path selection,awkfor known structured fields, andsedfor controlled text transformations. - Trace stdout and stderr separately. A pipe passes stdout by default, while
teecopies stdin to both its stdout and selected files. A here-document supplies multiline input to a command. - List archive member paths and verify restored bytes in a separate directory.
- Use
systemctlfor the manager's state andjournalctlfor accessible retained logs. Enablement and runtime activity are different observations. - Use
ssfor local sockets and the intendedcurlrequest for HTTP. Usedf,du,findmntandlsblkfor different storage questions. - Check schedule fields, timezone, interpreter and environment. Verify the receiver and exact path before a real transfer.
- Test a script with known valid and intentionally failing inputs, and compare what it published.
Got it? grep, awk, pipes, services, cron and scripts – these are a cloud engineer's everyday weapons. Now let's move on to the most important service in AWS – EC2.
समजलं का? grep, awk, पाइप्स, सर्व्हिसेस, cron आणि स्क्रिप्ट्स – हेच क्लाउड इंजिनिअरचे रोजचे हत्यार आहेत. आता पुढे जाऊया AWS मधल्या सगळ्यात इम्पॉर्टंट सर्व्हिसकडे – EC2.
समझ आया? grep, awk, पाइप्स, सर्विसेस, cron और स्क्रिप्ट्स – यही क्लाउड इंजीनियर के रोज़ के हथियार हैं. अब आगे चलते हैं AWS की सबसे इम्पॉर्टेंट सर्विस की तरफ़ – EC2.
Prepare an inspection handover someone else can reproduce
You are preparing a handover for the afternoon workshop shift. One file contains a small access record for the inspection dashboard. Two project folders sit on the practice machine, one owned by the workshop and the other by a library team. Your assignment is to select the workshop's files, count the requests with a particular status, verify a report, and package it for another operator. The library files are outside your change scope. A handover succeeds when the receiver can find the exact paths, verify the contents, and explain how the numbers were obtained.
The exercises build toward this result in one Bash session. They use only newly created local files and ordinary Unix utilities. A Linux machine is useful for optional observations about services and mounts, while the core data, comparison, and archive lab also works on other Unix-like practice machines. You do not need an EC2 account, current web server, administrative access, or a published endpoint. Use the same terminal for the variable holding the scratch directory. Read the expected outcomes before deciding that a command completed the task.
Write four lines in your own notes before you begin. The source is the workshop's records/access.sample under the generated directory. The report will be a separate file under workshop/delivery. The restorable package will sit outside that delivery subtree. The library marker will be compared with an independent original copy. These four facts make the scope observable. Out-of-scope files can still be readable or writable to your Unix account, so filesystem permission alone does not identify what the exercise authorizes.
practice_lab=$(mktemp -d) || exit 1
printf 'Lab directory: %s\n' "$practice_lab"
mkdir -p "$practice_lab/workshop/records" "$practice_lab/workshop/delivery" \
"$practice_lab/workshop/archive" "$practice_lab/library"
cat > "$practice_lab/workshop/records/access.sample" <<'LOG'
08:00 192.0.2.10 200 /health
08:01 192.0.2.11 404 /missing
08:03 192.0.2.10 200 /notes/404.txt
08:08 192.0.2.12 503 /worksheet
08:12 192.0.2.11 404 /archived
LOG
printf 'site=workshop.example.test\n' > "$practice_lab/workshop/current.conf"
printf 'site=retired.example.test\n' > "$practice_lab/workshop/archive/retired.conf"
printf 'site=library.example.test\n' > "$practice_lab/library/current.conf"
cp "$practice_lab/library/current.conf" "$practice_lab/library.expected"
printf 'Keep this previous handover until a new report is verified.\n' \
> "$practice_lab/workshop/delivery/report.txt"
cat "$practice_lab/workshop/records/access.sample"
The generated directory line varies. The source log contains five data rows, each with four whitespace-separated fields: time label, recorded IPv4 address, numeric HTTP status, and path. Those columns are part of this fixture's own contract. It is not a general Nginx access format. The address block is reserved for documentation, so it is safe to read its fictional values without making network requests. A path includes the digits 404 on purpose. Your query must identify the status field and not count that path as an error response.
Work through the rows by hand once. Two requests have status 200, two have status 404, and the one worksheet request has status 503. Both 404 responses are recorded against the same address. The supplied data includes three distinct recorded addresses. A report about a different category, such as all failed HTTP responses, would need an explicit rule for including 503 as well. Do not let the familiar status code determine a wider business definition that was never requested.
Exercise 1. Find the correct files and isolate the requested field
First list the workshop configuration files while excluding its archived copy. Stay inside the workshop parent. Try writing the find expression before opening the answer. The output should contain only ./current.conf. A suffix match scoped to the workshop still includes the archived file unless you exclude that directory or explicitly restrict depth. If the active config is known to be one exact file, that file's path is already stronger evidence than an unrestricted search.
Check the scoped file selection
(
cd "$practice_lab/workshop" || exit 1
find . -type d -name archive -prune -o \( -type f -name '*.conf' -print \)
)
The expression first identifies the named archive directory and prunes it. The second side selects only regular files with the specified suffix and prints the accepted path. The shell quotes the pattern so it stays available for find's traversal instead of expanding earlier in the present directory. The starting point does not include the sibling library tree. If the project later uses an approved include pattern, consult that actual configuration to determine which files are live. This command demonstrates a bounded selection for the fixture, not an inventory of a real server's parsed configuration.
Next, distinguish a literal substring count from the number of responses with an exact status. Compare a grep count for the substring 404 with an awk count constrained to field three. Ask which result answers the workshop request and why the other is larger. This is a proof exercise: the fixture was chosen so the two answers cannot happen to agree.
Check both counts and the matching request paths
grep -Fc -- '404' "$practice_lab/workshop/records/access.sample"
awk '$3 == "404" { count++; print $2, $4 } END { print "status-404=" count+0 }' \
"$practice_lab/workshop/records/access.sample"
3
192.0.2.11 /missing
192.0.2.11 /archived
status-404=2
The first count includes the successful request for /notes/404.txt. The projection in awk prints the recorded address and path for the rows whose status field equals 404. The output identifies both counted rows, which lets a reviewer verify the total independently. A line count for a different field could still appear plausible. Check the writer's log specification before adopting these exact field positions elsewhere, especially when quoted values or optional columns change what plain whitespace splitting means.
Exercise 2. Produce a tally and verify the output before promotion
The report needs one row per status, in numeric status order, with a count and the status separated by a single space. For the supplied fixture the status 200 has two rows, 404 has two, and 503 has one. Write that expected result before writing the pipeline. This checks all three groups. If you check only that the counts add to five, a sequence containing multiple separate rows for one status can still satisfy the weaker total.
The approved source has a known record layout and every status is a three-digit value in its expected range. A malformed record should prevent publication. For the exercise, use a validating awk stage to emit only the status, a sorting stage to arrange equal statuses, uniq to count adjacent occurrences, and a final projection to normalize output spacing. After running the pipeline, compare the candidate with the independently prepared expectations. The stable expected ordering here uses the three-digit status as the sort key, which makes lexical ordering equivalent to numeric ordering under these inputs.
Check the validating pipeline and its expected report
printf '%s\n' '2 200' '2 404' '1 503' > "$practice_lab/expected-report.txt"
cat > "$practice_lab/validate-statuses.awk" <<'AWK'
NF != 4 || $3 !~ /^[1-5][0-9][0-9]$/ { invalid++; next }
{ valid++; print $3 }
END { if (invalid || !valid) exit 3 }
AWK
if (
set -o pipefail
LC_ALL=C awk -f "$practice_lab/validate-statuses.awk" \
"$practice_lab/workshop/records/access.sample" \
| LC_ALL=C sort | uniq -c | awk '{ print $1, $2 }'
) > "$practice_lab/candidate.txt" 2> "$practice_lab/pipeline-error.txt"; then
if cmp "$practice_lab/expected-report.txt" "$practice_lab/candidate.txt"; then
printf 'Candidate matches all expected status groups\n'
cat "$practice_lab/candidate.txt"
else
printf 'Inspect the result before publishing\n' >&2
fi
else
printf 'Pipeline failed. Read the diagnostics and input format.\n' >&2
fi
Candidate matches all expected status groups
2 200
2 404
1 503
The awk stage can emit some statuses before discovering a bad record. Its final status is therefore an essential part of the pipeline result. With pipefail, a failure in this earlier stage causes a nonzero combined result despite the later counting stages successfully processing the bytes they received. Do not use the presence of a candidate to establish success. The shell opened that path before the pipeline ran. The validation also requires a meaningful number of records, because a blank file should not silently replace a valid handover in this exercise.
The last awk prints exactly two fields per tally row, with one separator. That step removes implementation-specific padding from uniq. Sorting ensures identical statuses are adjacent. Status and count ordering are separate. Here the requirement orders by status number. Ranking by count would need a second sort with a stated tie rule. If asked for the most common failure, first decide what values qualify as failures, and then rank the results from that defined set. Each step should express one documented part of the question.
Check the previous report is still the sample line you created. No promotion has occurred yet. When your candidate comparison succeeds, install the reviewed file in the scratch delivery tree and verify it again. Keep the output path explicit. This is a local exercise with one user and no reader that needs an atomic publication contract. A service reading concurrently would need an appropriate same-filesystem candidate and documented synchronization.
Check the publication boundary
cat "$practice_lab/workshop/delivery/report.txt"
if cmp "$practice_lab/expected-report.txt" "$practice_lab/candidate.txt" \
&& cp "$practice_lab/candidate.txt" "$practice_lab/workshop/delivery/report.txt" \
&& cmp "$practice_lab/expected-report.txt" "$practice_lab/workshop/delivery/report.txt"; then
printf 'Verified workshop deliverable\n'
fi
cmp "$practice_lab/library.expected" "$practice_lab/library/current.conf" \
&& printf 'Library marker unchanged\n'
Keep this previous handover until a new report is verified.
Verified workshop deliverable
Library marker unchanged
This check proves the specific scratch report and comparison marker. It does not say that a live app has learned about the report. There is no live app in this local exercise. A production handover would define who reads the new file, the required access and paths, and how the resulting user action is verified. Practicing exact field assertions on a small example is how you can make the broader handover reviewable.
Exercise 3. Build and restore the deliverable package
The next operator needs the report and a short explanation of its scope. Prepare a file named scope.txt with two facts. It should identify the input as workshop access records and state what the report lines mean. Package those two deliverable files only. The raw records and old configurations are not part of this shareable package. The library site belongs to another project. Limiting the archive to listed files makes that boundary easy to inspect.
Choose a parent directory for tar's path calculation. In this lab it will be the scratch parent, so its members should read workshop/delivery/report.txt and workshop/delivery/scope.txt. The candidate archive itself lives outside the delivery path. Compare the actual listing with an independently written two-line expected list. If the listing includes a config backup or the unrelated library marker, fix the archive selection rather than asking the recipient to ignore the extra files.
Check the archive source and list before restoring
printf '%s\n' 'Source: workshop inspection dashboard access records' \
'Format: count followed by HTTP status' > "$practice_lab/workshop/delivery/scope.txt"
printf '%s\n' 'workshop/delivery/report.txt' 'workshop/delivery/scope.txt' \
> "$practice_lab/expected-members.txt"
tar -c -z -f "$practice_lab/shift-handover.tar.gz" -C "$practice_lab" \
workshop/delivery/report.txt workshop/delivery/scope.txt
if tar -t -z -f "$practice_lab/shift-handover.tar.gz" > "$practice_lab/members.txt" \
&& cmp "$practice_lab/expected-members.txt" "$practice_lab/members.txt"; then
cat "$practice_lab/members.txt"
fi
workshop/delivery/report.txt
workshop/delivery/scope.txt
The specified inputs are two regular files. -C identifies their common filesystem view and the relative strings following it define the stored member names. No directory is archived recursively in this example. Tar's gzip layer provides a compressed form of the archive. A single archive path can hold both files and their directory prefixes even though the files are separate when received. Confirm that the member names reflect the desired recovery structure.
Create a new restore directory and extract the archive there. Verify the report against the original independent expected values, and verify the scope against the reviewed source. Check that the raw access sample and library config did not appear in the restore. Their absence matters because a report recipient needs only the approved two files. Maintain the source and recovery paths separately throughout the exercise so a success comparison cannot accidentally compare a file with itself.
Check bytes and absence of out-of-scope files
mkdir "$practice_lab/receiver"
if tar -x -z -f "$practice_lab/shift-handover.tar.gz" -C "$practice_lab/receiver" \
&& cmp "$practice_lab/expected-report.txt" "$practice_lab/receiver/workshop/delivery/report.txt" \
&& cmp "$practice_lab/workshop/delivery/scope.txt" "$practice_lab/receiver/workshop/delivery/scope.txt" \
&& [ ! -e "$practice_lab/receiver/workshop/records/access.sample" ] \
&& [ ! -e "$practice_lab/receiver/library/current.conf" ]; then
printf 'Restored report and scope match. Other fixture data remained outside the package.\n'
fi
cat "$practice_lab/receiver/workshop/delivery/report.txt"
Restored report and scope match. Other fixture data remained outside the package.
2 200
2 404
1 503
Successful extraction proves that this reader can open the archive and place the files at the expected paths. Exact byte comparisons prove the content equality for this lab. Neither observation is proof that another operating system will preserve every kind of metadata, or that a live service can read the files with its own account. If you extend the exercise to a real restore, test the needed metadata and application result with the actual target environment. Keep the archive's identity and the known expected version available to the receiver.
Exercise 4. Explain where each command would run
A coworker asks you to prepare the handover automatically on Sunday evenings. First clarify the time and timezone and whether the job runs every weekday or has a special calendar rule. For a weekly 23:00 Sunday schedule in the applicable clock, the conventional five fields are 0 23 * * 0. For 23:00 Sunday India Standard Time with a UTC scheduler, use 17:30 Sunday UTC, corresponding to 30 17 * * 0. Both describe Sunday in this case, though an earlier local time could cross the UTC day boundary. Write the schedule in notes and avoid installing a persistent job as part of this local handover lab.
Now identify the environment of the proposed command. It could run as a separate scheduled account with another current directory, a smaller search path, and no interactive aliases. A working relative path in the current terminal is a weak demonstration. Run a read-only check with a minimal environment and one actual absolute file path as an argument. The command should still read the verified report. It should fail when you deliberately supply a nonexistent path. Treat the exit result as separate evidence from the displayed data.
Rehearse a minimal-environment read without scheduling it
env -i PATH=/usr/bin:/bin /bin/sh -c 'cat "$1"' delivery-check \
"$practice_lab/workshop/delivery/report.txt"
if env -i PATH=/usr/bin:/bin /bin/sh -c 'cat "$1"' delivery-check \
"$practice_lab/workshop/delivery/absent.txt" 2> "$practice_lab/delivery-error.txt"; then
printf 'Unexpected readable missing-file fixture\n'
else
printf 'missing deliverable status=%s\n' "$?"
fi
cat "$practice_lab/delivery-error.txt"
2 200
2 404
1 503
missing deliverable status=1
A missing-file diagnostic appears after the expected lines. Its wording and actual path depend on your system. The explicit shell argument after delivery-check is the file intended for that run. env -i changes inherited variables. It does not switch the user's permissions, the filesystem view or a real scheduler's other conditions. That is enough for this demonstration because the command's only known requirements are an executable found on PATH and a named input it is allowed to read.
Exercise 5. Show that a failure does not become a delivered report
Now act as a reviewer trying to break a weak solution. An input could contain a status word such as retry rather than a numeric status. If a malformed line is simply skipped and the rest counted, the unchanged-looking counts can be misleading. Create a separate attempted input and append one deliberately invalid record. Keep the approved source and published report in place. Your test should exercise the same validator while selecting a new attempted result path.
Check that malformed input yields a failed combined status
cp "$practice_lab/workshop/records/access.sample" "$practice_lab/invalid.sample"
printf '%s\n' '08:15 192.0.2.10 retry /health' >> "$practice_lab/invalid.sample"
if (
set -o pipefail
LC_ALL=C awk -f "$practice_lab/validate-statuses.awk" "$practice_lab/invalid.sample" | wc -l
) > "$practice_lab/invalid-count.txt"; then
printf 'Unexpected valid report input\n'
else
printf 'invalid candidate status=%s\n' "$?"
fi
cat "$practice_lab/invalid-count.txt"
cmp "$practice_lab/expected-report.txt" "$practice_lab/workshop/delivery/report.txt" \
&& printf 'Previously published report preserved\n'
invalid candidate status=3
5
Previously published report preserved
The count display can have padding. The validator emitted five acceptable records, which the counter processed. At the end the validator still rejected the full input due to one invalid record. The counter's successful arithmetic is no reason to adopt the partial content. The reported status of three comes from the validator in this case, and the last comparison proves that the prior published artifact did not change. Separate the rejected output name from the approved report name so a person reviewing the error cannot mistake one for the other.
Next plan a similar exercise for a nonempty report with the right arithmetic but the wrong source. A second folder could have five different requests with the same counts. A sorted tally can be exactly equal while events and ownership differ. Your evidence should record which path and input data actually fed the query. Counts identify the derived report, not the identity of the source. If provenance matters, keep an expected input digest or a checked sample plus metadata rather than trying to infer provenance by reading the final three numbers.
Consider a third negative control in which the archive is valid but the package includes an unnecessary file. The listing assertion should fail even if the recipient can open the report and scope. Unlike an intentionally corrupt archive, this wrong-scope archive might pass every format integrity check. Test what the delivery requires, not just the container mechanics. Do not include the wrong package in a real transfer, and keep any diagnostic examples inside the scratch directory when you experiment further.
Exercise 6. Trace an operations question without changing anything
Use these paper cases to connect the hands-on report to a web deployment. A teammate says the workshop service is enabled but its page will not open. List the independent observations you would need. Is its service unit loaded and active, and what is its substate? Is the wanted socket listening for the intended address and protocol? What does a request for the actual hostname, method, and path return? Does the intended application generate a matching log entry? Checking enablement is appropriate for a startup question, while the request uses several later steps.
Now add a concrete case. The backend answers an authorized request at http://127.0.0.1:8123/health on the host. The intended users access an HTTPS front end with a different host name. Ask which request worked and which failed. A local backend response says the backend can handle that local request. It does not show the public hostname resolved correctly, reached the front end, passed the connection and TLS steps, or selected the expected route. Read each of those observations from the correct context. If a wrong path exists nowhere on the backend, fixing name resolution alone would not fix that response.
A second teammate says the scheduled output ran out of space. The destination table indicates 15 GiB available under the mounted delivery data volume, but the job first assembles a 500 MiB candidate in a staging directory on a root filesystem with only 200 MiB available. Identify which path needs capacity at each stage. Use df on the exact existing staging and data parent paths and confirm the expected mount. Check inode counts if relevant. A plausible large capacity elsewhere does not help the intermediate write. Review the writer's space requirement and mount context before moving anything or removing files.
In a third case the machine responds slowly during the job even though the simple dashboard shows 25 percent CPU use on a four-vCPU guest. Ask whether the report is single-threaded and saturates one logical CPU. Also check process CPU time, task states, and the same interval's actual response duration. A storage wait or memory limit can cause another kind of slowdown even with low CPU use. This is an observation plan, not a performance verdict. No need to run artificial load on an existing shared machine to answer the paper case.
Exercise 7. Write an independent check for the three observed statuses
A workshop handover should not rely on verifying a transformation with a copy of the same transformation. For the small fixture, one independent check is a Bash loop with separate counters for the three allowed statuses in this exercise. Its job is deliberately limited to these rows. For a general web log, you would need a format-aware parser and documented classification for all statuses. Here the narrow implementation lets you test how a loop, quoted fields, and conditional output work together without reusing the awk pipeline's grouping logic.
Start all three counters at zero. Read the fields from the known whitespace format and reject a row if it lacks a field or has additional words. Decide what to do with a status outside the three fixture values. In the example it fails this exercise-specific comparison. After the loop, emit the three groups in the order the handover expects. Use a separate candidate path for the reviewer result. If the function or loop fails, preserve the published report and record why the independent check could not complete.
Check the independent Bash loop
if (
ok_count=0
missing_count=0
unavailable_count=0
while read -r stamp address status route extra; do
if [ -z "$stamp" ] || [ -z "$address" ] || [ -z "$route" ] || [ -n "$extra" ]; then
printf 'Unexpected row layout\n' >&2
exit 2
fi
case "$status" in
200) ok_count=$((ok_count + 1)) ;;
404) missing_count=$((missing_count + 1)) ;;
503) unavailable_count=$((unavailable_count + 1)) ;;
*) printf 'Unexpected fixture status\n' >&2; exit 2 ;;
esac
done < "$practice_lab/workshop/records/access.sample" || exit 2
printf '%s 200\n%s 404\n%s 503\n' "$ok_count" "$missing_count" "$unavailable_count"
) > "$practice_lab/review-report.txt" \
&& cmp "$practice_lab/workshop/delivery/report.txt" "$practice_lab/review-report.txt"; then
printf 'Independent loop agrees with the delivered report\n'
fi
Independent loop agrees with the delivered report
The known setup produces Unix line endings and exactly one newline-terminated record per event. The while loop's input is opened by a redirection on the loop, so it can update the counters in the surrounding subshell. If the input open fails, the guarded operation exits with a failure. The counters remain visible to the final printf in that same subshell. A loop placed in a pipeline could run in a different shell environment depending on shell options. Test the chosen structure rather than assuming that a variable increment transfers across processes.
The loop and pipeline use distinct counting mechanics, while they still share the same source and documented field positions. They can agree and still be unsuitable if you chose the wrong source. Combine this comparison with the explicit scope and expected-results check. A test suite is strongest when each test catches a different class of mistake. Here exact known counts, a rejected invalid line, artifact scope, and an independent counting method cover different risks. Change one input row and predict how both implementations should respond before rerunning them.
Exercise 8. Revise the wording without replacing the accepted package
After the report is delivered, someone asks for the description to use the phrase “request count” instead of “count” in the second line. The approved package should remain available while you review the new wording. The exercise writes a new scope.candidate.txt outside the delivery tree. Choose an anchored substitution that changes only the exact format line. Do not search and replace a general word across the entire project. A separate preview and a comparison are the meaningful evidence before anyone prepares a new package.
Check the proposed wording and the retained source
sed 's/^Format: count followed by HTTP status$/Format: request count followed by HTTP status/' \
"$practice_lab/workshop/delivery/scope.txt" > "$practice_lab/scope.candidate.txt"
if grep -Fx -- 'Format: request count followed by HTTP status' "$practice_lab/scope.candidate.txt" \
&& grep -Fx -- 'Format: count followed by HTTP status' "$practice_lab/workshop/delivery/scope.txt" \
&& cmp "$practice_lab/workshop/delivery/scope.txt" "$practice_lab/receiver/workshop/delivery/scope.txt"; then
printf 'Candidate verified while the accepted scope remains unchanged\n'
fi
Format: request count followed by HTTP status
Format: count followed by HTTP status
Candidate verified while the accepted scope remains unchanged
The first match is in the preview and the second in the original. A reviewer could use a unified diff to inspect whether any other line changed. The recovered file matches the current accepted original, which helps keep archive and installed content separate from the proposed wording. A new candidate does not on its own alter the original archive. If a team approves a revised deliverable, give the new package its own explicit version and repeat the member and restore checks. This exercise stops at a verified candidate.
Exercise 9. Test a changed reporting requirement against a boundary
The supervisor asks a follow-up question about the first five minutes shown in the exercise. The original delivered report covers every supplied row. The new result should describe requests from 08:00 inclusive until 08:05 exclusive in the source's agreed clock. A timestamp at 08:05 belongs to the next window. Write that rule down, because words like “through 08:05” can be interpreted differently. Keep both reports distinguishable. A new answer computed from fewer rows does not correct or replace the old answer to the broader question.
The supplied labels use fixed-width, zero-padded hour and minute text on the same day. Sorting or comparing those characters can reflect time order under those restricted conditions. The example below converts the validated label to a minute of the day so the interval is explicit. For a data source that includes dates, offsets, fractional seconds or daylight-saving transitions, use a timestamp parser that represents the actual date and timezone. This lab intentionally uses a simpler format whose limitations you can explain to a reviewer.
Make a new input from the same log and insert a fourth event with a time label of 08:05. The new line should be excluded by the requested upper boundary. Place it after the other rows to emphasize that filtering does not depend on the input being sorted. The unchanged original input is still the source of the published tally. Compare the selected lines, the number of included requests, and the number of included 404 responses against hand-counted expectations.
Check the lower and upper boundary behavior
cp "$practice_lab/workshop/records/access.sample" "$practice_lab/window.sample"
printf '%s\n' '08:05 192.0.2.10 404 /boundary' >> "$practice_lab/window.sample"
LC_ALL=C awk -v from=480 -v until=485 '
NF != 4 || $1 !~ /^[0-9][0-9]:[0-9][0-9]$/ {
bad++
next
}
{
split($1, clock, ":")
if (clock[1] + 0 > 23 || clock[2] + 0 > 59) {
bad++
next
}
minute = 60 * clock[1] + clock[2]
if (minute >= from && minute < until) {
selected++
if ($3 == "404") missing++
print $1, $3, $4
}
}
END {
if (bad) exit 2
printf "selected=%d status-404=%d\n", selected + 0, missing + 0
}
' "$practice_lab/window.sample"
08:00 200 /health
08:01 404 /missing
08:03 200 /notes/404.txt
selected=3 status-404=1
The start of the interval is eight times sixty, or 480 minutes after midnight. Its upper boundary is 485. The script checks the shape of the time label and the ranges of hours and minutes before using a value. The record at 08:00 is included, while the explicitly added 08:05 line is excluded. An ordinary string search for the digits 404 within the selected time range would still count the digits in the successful notes path. That is a separate field-selection problem, even when the time filter is correct.
The code can emit selected rows before discovering a malformed time; when adapting it for a report directory, stage its output and check its exit status before publishing. Under the fixture input all rows have an established valid address, status, and path. This follow-up checks time behavior specifically. In a real report, keep the earlier validation contract for the other fields rather than assuming that a valid time proves the entire record. You can combine the checked validation steps in a single documented parser once you have precise requirements for the complete source format.
Test a second change on paper before editing. If the regular shift is from 23:58 until 00:03 the next day, expressing the rule as one numeric range on minute of day is inadequate. The number wraps at midnight. A reporting source with dates should represent the complete interval across those two days. If the analysis also needs to handle a repeated local hour, explicit offsets or an unambiguous time zone and documented rule matter. A test that happens to pass for an ordinary morning does not establish that overnight case. Choose the representation that supports the intended data.
For the handover, state both questions and answers. The original report counts every supplied request and groups by status. The follow-up selects three requests in the early window and counts one 404. Keep its separately tested boundary mentioned in the notes and compare the original published report with its expected bytes if someone claims the later work changed it. The local archive still represents only the approved initial report and its scope. No follow-up artifact belongs in it unless the recipient explicitly requests a new revision.
To extend this check, change one sample row to the label 08:60 in a separate copy. The command should report nonzero even if other selected rows looked reasonable. If a script built its output directly at the accepted path, this failure could leave a partial handover. Practice separating the window candidate from the general delivery. The independent fixture and controlled errors give you evidence for the changed requirement rather than a second plausible number with no explanation.
Exercise 10. Plan a verified transfer without changing the live account
The receiver might be another authorized machine rather than a local recover folder. The same report and scope need to arrive without the raw data or library files. Identify what would live on each side. Your verified source archive and your private SSH identity are local. The intended destination belongs to the receiver's approved training account. The transfer status, received filename and verified bytes are separate observations. A local copy to the wrong path can succeed. An SSH login alone says nothing about which artifact was copied.
Write a sample client config in the scratch directory and inspect the evaluated identity fields with OpenSSH's offline preview. The reserved documentation address, account label and port here describe format only. They are not a destination to contact. No private key material is created or read for this test. If you continue into the dedicated SSH lesson using an approved receiver, obtain its verified host identity, use a fresh scoped destination, and compare the copied archive and its member names. Use the dedicated lesson's existing local-to-remote boundary rather than guessing at a real shared home directory.
Verify the offline transfer profile syntax
if command -v ssh >/dev/null 2>&1; then
cat > "$practice_lab/receiver.conf" <<'SSH'
Host shift-receiver
HostName 192.0.2.42
User trainee
Port 2222
StrictHostKeyChecking ask
SSH
chmod 600 "$practice_lab/receiver.conf"
ssh -G -T -F "$practice_lab/receiver.conf" shift-receiver \
| awk '$1 == "hostname" || $1 == "port" || $1 == "user" { print }'
fi
user trainee
hostname 192.0.2.42
port 2222
The order of these fields may vary. The command exits after showing the resolved settings. It does not contact the documented address. If ssh is not available, inspect the file format on paper and mark this stage as an optional observation. A live destination would require an authorized account and a host verification procedure. A local config parse cannot prove either remote authentication or trust. Distinguish that rehearsal from the locally verified archive restore, which already establishes content for the two files.
For a repeated transfer decision, compare scp and rsync using the actual task. Scp is sufficient for one checked new archive. Rsync can preview and synchronize a set of paths when both ends support the necessary mode. Its file comparison and path rules depend on options, so establish exactly what belongs in the target and inspect a dry run before choosing it. In particular, a trailing slash on the rsync source can change whether the destination receives a directory name or just its contents. On a shared host confirm that no outside path participates. Avoid adding a destructive retention action to an otherwise additive training transfer.
Finish with an evidence sheet and a narrow cleanup
The handover sheet should include the exact source scope, expected groups, actual compared results, member names, and the library boundary. Each entry should have an observation that another person can reproduce. Avoid a generic checkmark for success. For example, record “the archive listing contains only report and scope under workshop/delivery” so a reviewer knows which property was tested. Record separately that the restored report matches the three expected lines. These checks remain useful if the restored path changes later.
| Evidence item | Expected result in this exercise | If it differs |
|---|---|---|
| File selection | Workshop current config only, with archive and sibling outside the selection. | Review the traversal root and prune logic before further operations. |
| Literal versus exact status count | Three matching text lines, two rows with an actual 404 status. | Inspect the fixture format and the selected field. |
| Validated report | Two 200, two 404 and one 503, each as its own group. | Inspect input validation, stage statuses and grouping order. |
| Negative input | Partial count reported with status three and old report byte checks passing. | Keep both results separate and repair the failure decision. |
| Restored delivery | Only the expected two files, with exact stored paths and matching content. | Compare the member list and target directory before repackaging. |
| Project boundary | Library marker still matches its separately saved copy. | Stop and review which path each command opened. |
Have a second learner repeat the comparison using only your notes and the two restored files. They cannot recompute the original counts without the source, which the received package correctly excludes. They can check the reported figures against the independent expected values you recorded and verify the scope note they received. If their assignment requires reproducing every raw input step, provide an approved synthetic fixture separately instead of transferring a real log that may contain data they do not need. The distinction between checking an artifact and recomputing it is part of a good evidence sheet.
Record the output format as count followed by status and retain its sort order. A person who accidentally swaps those fields can still read three plausible numeric lines. Describing exact column meaning prevents that error when the report is imported into another tool. If you notice an incomplete output in any earlier exercise, trace back to the generating command and evidence for its status before rerunning the final package step. Packaging a candidate makes it easier to share, but preserves its mistakes along with its data.
If a failure appears, first classify it. An argument problem occurs before the report stage. Invalid input can allow some rows through but must reject publication. A packaging error can produce an archive with the wrong contents even when creation succeeded. A read failure on the receiver can reflect the expected path, account permissions, or incompatibility with the chosen format. Keep the original input, last verified output, latest candidate, and their evidence distinguishable while fixing the problem. That way the repair can be verified against the same acceptance criteria.
Before cleanup, check the generated path and verify that your results have been recorded. The commands only clear exact files and directories created by the lab. They do not remove the initial parent of the scratch folder or affect any schedule. If a file in the recovery tree remains because you made an additional exercise copy, rmdir leaves the affected directory in place. Inspect that copy and remove only the artifact you created after you no longer need it. This design makes teardown another bounded operation rather than a broad deletion test.
if [ -n "${practice_lab:-}" ] && [ -d "$practice_lab" ]; then
printf 'Cleaning practice files in %s\n' "$practice_lab"
rm -f -- "$practice_lab/workshop/records/access.sample" "$practice_lab/workshop/current.conf" \
"$practice_lab/workshop/archive/retired.conf" "$practice_lab/library/current.conf" \
"$practice_lab/library.expected" "$practice_lab/workshop/delivery/report.txt" \
"$practice_lab/workshop/delivery/scope.txt" "$practice_lab/receiver/workshop/delivery/report.txt" \
"$practice_lab/receiver/workshop/delivery/scope.txt" "$practice_lab/expected-report.txt" \
"$practice_lab/validate-statuses.awk" "$practice_lab/candidate.txt" "$practice_lab/pipeline-error.txt" \
"$practice_lab/expected-members.txt" "$practice_lab/shift-handover.tar.gz" "$practice_lab/members.txt" \
"$practice_lab/delivery-error.txt" "$practice_lab/invalid.sample" "$practice_lab/invalid-count.txt" \
"$practice_lab/review-report.txt" "$practice_lab/scope.candidate.txt" "$practice_lab/receiver.conf" \
"$practice_lab/window.sample"
rmdir -- "$practice_lab/workshop/records" "$practice_lab/workshop/archive" \
"$practice_lab/workshop/delivery" "$practice_lab/workshop" "$practice_lab/library" \
"$practice_lab/receiver/workshop/delivery" "$practice_lab/receiver/workshop" \
"$practice_lab/receiver" "$practice_lab"
fi
unset practice_lab
Review questions
Interview question. What makes the grep result differ from the status result?
Grep matches the text 404 anywhere in each line. One successful request contains those digits in its path. The awk report matches only the documented third field, yielding two actual requests with status 404. The result depends on the input format and the stated question.
Interview question. Which checks prove the archive belongs to this assignment?
List exactly the two expected relative members and restore them into a new separate directory. Compare the bytes and verify that the raw sample and neighbor do not appear in the restore. A successful gzip or tar integrity check alone would leave scope and contents unverified.
Quiz. The validation pipeline left five lines in the rejected candidate. Why was rejection still appropriate?
The script detected a sixth row whose status was outside the expected format and returned a failure. The counter processed valid emitted data, which is insufficient to accept the full report. The candidate was separate, so the previous result remained available.
Quiz. Which exact action can you practice without connecting to the example SSH destination?
Use OpenSSH's effective configuration preview to confirm the host alias, user and port. The given address is reserved for documentation. The preview can be performed independently of any host authentication or file transfer.
Quiz. A scheduled process wrote nothing. What evidence would separate a missing launch from a failed read?
Look for the scheduler's record of dispatch and then the actual job's output or diagnostic. Check its account, path and working environment. A job can run and write no useful result because its input or output path was wrong, even when the schedule happened at the desired time.
Use a counterexample
Choose input where the quick count and actual status count disagree. That confirms the test is looking at the intended field.
Reject partial candidates
Inspect the validator's status, keep previous verified data, and compare a known final report independently.
Prove package scope
List expected members and check restored bytes. Select only the files the intended recipient needs.
Primary references
- GNU find actions and prune semantics
- GNU grep fixed-string and count modes
- POSIX awk field processing
- Bash pipelines, branches and quoting
- GNU tar archive creation and restore
- GNU cmp byte comparison
- Cronie schedule fields
- OpenSSH client preview and authentication
- Rsync project documentation
- Documentation-only IPv4 addresses