Linux Foundations / Write a Small Defensive Bash Report

Check input and return a useful status

Lesson 35 of 37. Open to read. No account needed.

An empty report might mean that there were no records. It might also mean that the input could not be read. A useful script makes that distinction visible through its diagnostic output and exit status.

You will build a small line-count script, check its valid and rejected inputs, and observe a separate synthetic processing failure. Then repair a quoted-input defect and test the repair with a spaced filename. Each run keeps stdout and stderr in separate owned files.

1. Make rejection and success explicit

Complete Run and explain a small Bash script and settle its cleanup. Use the same explicit /bin/bash invocation model; this task does not add execute access or use direct script execution.

The new if statement chooses commands according to another command's exit status. Status 0 means the condition succeeded; nonzero selects the other path. then begins the successful branch, optional else begins the alternative, and fi ends the statement. The semicolon before then separates it from the condition when both are written on one line.

The Bash builtin [, also called test in this form, checks a condition. Its final ] is a separate required argument. Spaces around each part matter. Learn the three selected checks before reading the script:

ConditionMeaning
[ "$#" -ne 1 ]The argument count is numerically not equal to one. Check count before reading $1.
[ ! -f "$1" ]The first argument does not currently resolve to a regular file.
[ ! -r "$1" ]The first argument is not currently readable for this execution context.

Here ! negates the file test inside [ ... ]. The quoted expansion keeps a spaced pathname as one operand. These file tests follow a symbolic link to its target. They do not prove ownership, safe provenance, file format or that the file will remain unchanged/readable when processing starts. Our separate owned-fixture checks still reject unexpected links and files. The checks are not a security guarantee or a race-free promise.

The exit builtin ends this script with the selected numeric status. This script uses 2 for an incorrect argument count, 3 for a failed input path/readability check, and 4 for a processing failure. These meanings are the script's own contract, not universal meanings of those numbers. Diagnostics go to stderr with the already-taught >&2 redirection.

2. Preserve failure through the processing pipeline

The processing pipeline reads the selected file with cat and counts newline characters with wc -l. Its input has one newline-terminated record per line. A newline count is not a parser for arbitrary data formats or proof that every record's contents are correct.

Earlier pipeline work showed that a successful final command can hide an upstream failure. Inside this new child script, set -o pipefail changes the pipeline result: it is zero only if all stages succeed, otherwise the rightmost nonzero stage's status. It does not change the parent's option. We do not rely on automatic errexit behavior for these decisions.

The new processing condition combines taught assignment with a focused command substitution bridge:

if VECTA_LAB_LINE_COUNT=$(cat -- "$1" | wc -l); then

This is an excerpt to read, not a complete command to paste at the prompt. $(...) runs the enclosed commands in a subshell environment and captures their stdout, removing trailing newlines. Stderr remains separate. The assignment-only command returns the substitution's status. The subshell inherits this child's pipefail setting, so the if decision sees an upstream cat failure even if wc successfully prints a zero count.

Capturing the count also lets the script withhold its report when processing fails. A failed pipeline might still have produced captured text; that text is not automatically a valid result. On success, the final printf writes the report. Its actual status becomes the successful branch/script status; there is no unconditional exit 0 afterward to hide a failed output write.

The line-count script checks one argument and the current regular-file/readability conditions before a captured pipeline. Rejections write diagnostics and return statuses 2 or 3; processing failure returns 4 without the count report. Successful processing permits a report write whose actual result determines success. The checks do not validate ownership, content or future access.

Read the arrows as decisions in this supplied script. Data on stdout, diagnostics on stderr and the numeric exit status are separate observations. Green paths follow passed conditions; blue branches identify this script's chosen failure statuses 2, 3 and 4. The arrows do not specify stream arrival order. The failed processing branch withholds this script's count report; other programs can produce partial stdout before failing. A report-write error must remain an actual failure, not be overwritten by a forced success status.

Exercise: count an owned text input and preserve each outcome

Goal: distinguish valid data, rejected input and processing failure through exact output, diagnostics and immediate status.

Starting state: use the normal nonzero-UID account in the declared full Ubuntu guest. The prior script task is settled, and the parent can create a fresh owned practice directory. All required script text and data are below.

Run one line at a time and stop after unexpected setup/file errors. Begin with the taught origins and guest checks:

type cd pwd printf set declare type id ps mkdir ls cat wc nano rm rmdir exit '[' bash
type -a ls
type -P ls
type -P bash

Require the expected Bash builtins, including printf, set, declare, exit and [, and the expected guest utilities. Accept only the understood color alias for ls, with no hidden function or other origin. In particular, cat and wc must not be custom wrappers/functions inherited by a child.

id -u
id -un
ps -p $ -o comm=
ps -p 1 -o comm=
set -o

Require the recorded ordinary account, Bash and systemd PID 1. Preserve the taught parent errexit/allexport/nounset/posix-off baseline and require parent pipefail off for this child-versus-parent comparison. Do not change the parent's options. The script will enable pipefail only inside its child.

Inspect the relevant names before a launch:

declare -p VECTA_LAB_LINE_COUNT
declare -p BASH_ENV
declare -p SHELLOPTS BASHOPTS

Require the first two names individually absent. Preserve any collision. The existing option variables must have the ordinary readonly declarations without export x; do not unset them. The previous lesson explains why --noprofile/--norc do not suppress BASH_ENV and why exported option lists could change child startup behavior. Keep those guards throughout.

Prepare the one input and the first script

Inspect the known parent and new task name:

ls -ld ~/linux-practice
ls -ld ~/linux-practice/validate-input-and-exit-status

Require the ordinary owned parent and the task absent. An existing entry belongs to the resume branch. After acceptance:

mkdir ~/linux-practice/validate-input-and-exit-status
ls -ld ~/linux-practice/validate-input-and-exit-status

Accept the new ordinary owned directory, then enter and check separately:

cd ~/linux-practice/validate-input-and-exit-status
pwd
ls -a

Require the exact recorded task path and only dot entries. Create the spaced input with three supplied newline-terminated records:

printf '%s\n' 'Workshop checklist' 'Confirm room' 'Print agenda' > 'session notes.txt'
ls -ld -- 'session notes.txt'
cat 'session notes.txt'
wc -l -- 'session notes.txt'

Require an ordinary owned single-link file, all three exact lines and three newlines. Keep the fixture's owner/read access known. The script's -f/-r checks do not replace this content/ownership inspection.

Confirm count-lines.sh absent in the inventory before opening it:

ls -a

After accepting the known input and absent script name:

nano count-lines.sh

Enter this complete script with a final newline. Do not paste the Markdown fences. Use the taught Ctrl+O, confirm the filename, then Ctrl+X:

#!/bin/bash
set -o pipefail
if [ "$#" -ne 1 ]; then
    printf '%s\n' 'Usage: count-lines.sh INPUT' >&2
    exit 2
fi
if [ ! -f "$1" ]; then
    printf '%s\n' 'Input must be a regular file.' >&2
    exit 3
fi
if [ ! -r "$1" ]; then
    printf '%s\n' 'Input must be readable.' >&2
    exit 3
fi
if VECTA_LAB_LINE_COUNT=$(cat -- "$1" | wc -l); then
    printf 'Lines: %s\n' "$VECTA_LAB_LINE_COUNT"
else
    printf '%s\n' 'Could not count input lines.' >&2
    exit 4
fi

Before any run:

ls -ld -- count-lines.sh
cat count-lines.sh
ls -a

Require the exact saved text, an ordinary owned single-link script with read access, and only recognized task files. No executable-mode change is needed. Inspect each newly created script the same way before its first run.

Run valid input and keep the two streams separate

Require valid.out and valid.err absent. The taught > and 2> create separate captures; they would truncate existing files, so a collision stops the run. After accepting the exact input/script and current directory:

/bin/bash --noprofile --norc count-lines.sh 'session notes.txt' > valid.out 2> valid.err
printf 'valid-input exit: %s\n' "$?"

Record the immediate actual status before inspecting anything else. Require 0 for the demonstrated successful run, then inspect both captures:

ls -ld -- valid.out valid.err
cat valid.out
cat valid.err
wc -l -- valid.out valid.err

Require ordinary owned single-link captures. Stdout is exactly Lines: 3 and one newline; stderr is empty, with zero bytes shown by ls. A line count of zero alone would not prove a file empty. The original input remains exactly the three supplied lines.

Reject a missing argument and a missing file separately

Predict which check runs first when there is no argument. Confirm no-argument.out and no-argument.err absent before:

/bin/bash --noprofile --norc count-lines.sh > no-argument.out 2> no-argument.err
printf 'no-argument exit: %s\n' "$?"

Require status 2, empty stdout and exactly Usage: count-lines.sh INPUT with a newline on stderr. Inspect both captures' ownership, link count, size and complete contents as in the valid case. The count guard ran before any $1 test; this is not a failure caused by accidentally expanding a missing argument.

Next require missing.txt, missing.out and missing.err all absent in the known task inventory. Do not delete a real file to create this example:

ls -a

After that absence check:

/bin/bash --noprofile --norc count-lines.sh missing.txt > missing.out 2> missing.err
printf 'missing-path exit: %s\n' "$?"

Require status 3, empty stdout and exactly Input must be a regular file. with a newline on stderr. Read and inspect the named captures; do not infer their contents from status alone. This path is distinct from the readability branch. No permission denial is deliberately created here.

Observe a separate processing-failure fixture

The real script checks a path before processing, but conditions can change or an operation can fail afterward. This separate child fixture deliberately starts at the processing condition using a known missing name. It does not claim that the normal prechecks accepted that missing file, and does not reproduce a race or ordinary-user readability denial.

Confirm pipeline-failure.sh, missing-after-check.txt, processing.out and processing.err absent with the task inventory. After acceptance:

nano pipeline-failure.sh

Enter the complete synthetic fixture, save and inspect its exact text and ordinary owned single-link identity before running it:

#!/bin/bash
set -o pipefail
if VECTA_LAB_LINE_COUNT=$(cat -- 'missing-after-check.txt' | wc -l); then
    printf 'Lines: %s\n' "$VECTA_LAB_LINE_COUNT"
else
    printf '%s\n' 'Could not count input lines.' >&2
    exit 4
fi

After the explicit absence/identity gates:

/bin/bash --noprofile --norc pipeline-failure.sh > processing.out 2> processing.err
printf 'synthetic processing-failure exit: %s\n' "$?"

Require status 4 and an empty ordinary owned processing.out. The stderr capture contains the actual cat diagnostic identifying the missing operand and the script's Could not count input lines. line. Exact utility error wording can vary; preserve it. Inspect size, complete contents and identity:

ls -ld -- processing.out processing.err
cat processing.out
cat processing.err
declare -p VECTA_LAB_LINE_COUNT
set -o

Require the parent course variable still absent and parent pipefail still off. The child captured wc's text, but the failed pipeline condition prevented that captured zero from becoming a misleading success report. The presence of a downstream count is not evidence that cat read its input.

Independent task: repair the quoted-input defect

Keep all guided files. Confirm repair-count.sh, repaired.out, repaired.err, repaired-missing.out and repaired-missing.err absent. The intended input remains the same checked spaced file, and missing.txt remains absent.

Create repair-count.sh in nano with this complete faulty starter. Inspect it as text and repair it before executing; there is no need to run an unquoted pathname against unknown data:

#!/bin/bash
set -o pipefail
if [ "$#" -ne 1 ]; then
    printf '%s\n' 'Usage: repair-count.sh INPUT' >&2
    exit 2
fi
if [ ! -f "$1" ]; then
    printf '%s\n' 'Input must be a regular file.' >&2
    exit 3
fi
if [ ! -r "$1" ]; then
    printf '%s\n' 'Input must be readable.' >&2
    exit 3
fi
if VECTA_LAB_LINE_COUNT=$(cat -- $1 | wc -l); then
    printf 'Lines: %s\n' "$VECTA_LAB_LINE_COUNT"
else
    printf '%s\n' 'Could not count input lines.' >&2
    exit 4
fi

Before hints or the answer:

  1. Find the single missing-quote defect. Explain why successful quoted path checks do not fix a later unquoted processing operand.
  2. Repair only that defect, save and inspect every line and file identity. Preserve the checks, stderr branches and child-local pipefail.
  3. Actually run the repaired script on 'session notes.txt', using fresh repaired.out/repaired.err. Capture its immediate status and verify the exact report plus empty stderr.
  4. Actually run the repaired script on absent missing.txt, using fresh repaired-missing.out/repaired-missing.err. Verify the rejection status, empty stdout and exact diagnostic. Recheck the unchanged original input and parent variable/options.

Success: distinguish the valid, argument-count, path and synthetic processing outcomes; complete the repaired valid/missing runs; preserve stdout/stderr/status as separate evidence. Counts alone do not prove content, and supplied output does not replace an actual blocked run.

Graduated hints

  1. Compare the exact operand given to cat with the operands in the file checks. A spaced string can be split again by an unquoted expansion.
  2. Keep the command's -- boundary and the pipeline; only the argument expansion needs its missing quotation marks.
  3. Reuse the explicit Bash invocation and immediate status pattern, but choose the independent capture names so no guided result is overwritten.

Check Your Understanding

  1. Why must argument count be checked before $1? What do -f/-r still fail to prove about an input?
  2. How can wc produce zero while cat failed, and why does this script avoid printing a success report in that situation?
  3. Why must $? be captured immediately, and why should the script preserve the final printf status rather than replace it with exit 0?

Answer and Reasoning

The repaired processing condition is this excerpt inside repair-count.sh:

if VECTA_LAB_LINE_COUNT=$(cat -- "$1" | wc -l); then

The checks had preserved the complete spaced path, but the faulty cat operand did not. Quoting that expansion makes processing use the same single pathname that was checked. It does not add ownership, format or future-access guarantees to the tests.

After saving and accepting the complete repaired file, original input, exact cwd and absent capture names, a complete valid run is:

/bin/bash --noprofile --norc repair-count.sh 'session notes.txt' > repaired.out 2> repaired.err
printf 'repaired valid-input exit: %s\n' "$?"

Require 0, then inspect the ordinary owned single-link captures:

ls -ld -- repaired.out repaired.err
cat repaired.out
cat repaired.err
wc -l -- repaired.out repaired.err

Require exactly Lines: 3 and one newline on stdout, and zero-byte stderr. After rechecking missing.txt and both new captures absent:

/bin/bash --noprofile --norc repair-count.sh missing.txt > repaired-missing.out 2> repaired-missing.err
printf 'repaired missing-path exit: %s\n' "$?"

Require status 3 and inspect both captures:

ls -ld -- repaired-missing.out repaired-missing.err
cat repaired-missing.out
cat repaired-missing.err
cat 'session notes.txt'
wc -l -- 'session notes.txt'
declare -p VECTA_LAB_LINE_COUNT
set -o

Stdout must be zero bytes, stderr exactly Input must be a regular file. plus a newline. The original three input lines remain intact, the parent variable remains absent and parent pipefail remains off.

Understanding-check feedback

  1. Count validation establishes that a first argument was supplied before the script reads it. -f/-r describe the current resolved file/readability conditions and follow symlinks; they do not establish ownership, content validity or race-free future access.
  2. wc can count the empty stream left by a failed cat. Pipefail makes the assignment condition nonzero; its captured text stays internal, and the else branch reports failure/status 4 instead of a false Lines: 0.
  3. Any later command replaces $?. The final report printf's real status must also remain visible: unconditional exit 0 could erase its write failure. Expected script statuses are a contract, while unexpected interpreter or output errors still require their actual diagnostics.

Diagnose and recover without broad repair

ObservationWhat to inspect
Status 2 with usage on stderrThe supplied argument count, before assuming a path problem.
Status 3 with the regular-file messageThe exact current path; a directory, missing name or unsuitable resolved target is not accepted.
Status 3 with the readability messageActual current access, without changing ownership/modes or elevating the script here.
Status 4 after processingActual utility diagnostic and pipeline stage; successful prechecks cannot guarantee later success.
A spaced input fails only after checksCompare quoting at processing with quoting at the checks.
Output contains text but status is nonzeroTreat it as failed/incomplete output until the contract and diagnostics establish its meaning.
An output name already existsInspect the recorded stage; do not blindly truncate prior evidence.

Cleanup and resume

Finish independent work first. There were no permission or parent-option changes to restore. Recheck the known parent/task identities, then enter and verify separately:

ls -ld ~/linux-practice
ls -ld ~/linux-practice/validate-input-and-exit-status

Require ordinary owned directories before:

cd ~/linux-practice/validate-input-and-exit-status
pwd

Require the exact recorded task path, then inventory and inspect:

ls -a
ls -ld -- count-lines.sh pipeline-failure.sh repair-count.sh 'session notes.txt'
ls -ld -- valid.out valid.err no-argument.out no-argument.err missing.out missing.err
ls -ld -- processing.out processing.err repaired.out repaired.err repaired-missing.out repaired-missing.err

Require only the sixteen recognized ordinary owned single-link files and dot entries. Read any contents whose stage is uncertain; preserve unexpected entries or unfinished evidence. Establish actual documented confirmation responses. Only after acceptance, remove the three scripts and input:

rm -i -- count-lines.sh pipeline-failure.sh repair-count.sh 'session notes.txt'

Each target has a separate prompt. Declining one does not cancel the rest; if stopping, decline every remaining prompt and do not start the next group. After the first group is accepted, remove the recognized captures:

rm -i -- valid.out valid.err no-argument.out no-argument.err missing.out missing.err

Proceed only after accepting that group; the same per-target/refusal rule applies:

rm -i -- processing.out processing.err repaired.out repaired.err repaired-missing.out repaired-missing.err

Inspect the remaining inventory:

ls -a

Require the task empty before returning and checking:

cd ~/linux-practice
pwd

Require the recorded shared-root path and inspect the task entry:

ls -ld -- validate-input-and-exit-status

Only after accepting that ordinary owned empty directory:

rmdir -- validate-input-and-exit-status

Retain the shared root and parent settings. There is no parent course variable to unset after the successful child-only task. On resume, inspect all retained script/input/capture states. Do not execute the faulty starter or overwrite existing captures to reconstruct missing evidence. A later status cannot recover an old one; a blocked readability branch remains unverified rather than being inferred from a different execution identity. For partial cleanup, remove only remaining recognized named files after their checks; do not recreate deleted evidence merely to match the inventory.

Sources and other study views

Bash 5.2 and nano 7.2 match the selected version families; distribution configuration can differ. The Coreutils manual is newer than the selected 9.4 tools, and only the established forms above are used. The supplied failure fixture isolates processing logic; it is not evidence that ordinary guest permissions or every failure branch have been exercised.

Revision reconstructs the validation and status decisions. Quick Reference retrieves the checks and named run forms.

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 99 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy