Chapter 4: Linux Advanced Commands
4.13 Basic shell scripting
In short: A shell script is a text file of instructions interpreted by a shell.
Put a repeated workshop task into a shell script, then test it with known inputs. This lesson makes an inspection report and checks that a failed update preserves the previous result.
Workshop चे वारंवार करायचे काम shell script मध्ये लिहा आणि ठराविक input देऊन तपासा. या lesson मध्ये inspection report तयार करा आणि update fail झाल्यावर आधीचा report टिकतो का ते पहा.
Workshop का बार-बार होने वाला काम shell script में लिखें और ज्ञात input से जाँचें। इस lesson में inspection report बनाएँ और देखें कि update विफल होने पर पिछली report बची रहती है।
A shell script records commands, conditions, loops, and error handling. Linux EC2 user data can also contain a shell script. Its command timing and environment depend on the image and its initialization setup.
#!/bin/bash
if [ "$#" -ne 1 ]; then
printf 'Usage: %s NAME\n' "$0" >&2
exit 2
fi
printf 'Preparing a worksheet for %s\n' "$1"# After creating the scratch script in the workshop exercise
bash -n "$script_lab/workshop-report.sh"
bash "$script_lab/workshop-report.sh" "$workshop_data"| Concept | Syntax |
|---|---|
| Variable | NAME="Asha", use $NAME or ${NAME} (no spaces around =) |
| Command output | TODAY=$(date +%F) |
| Arguments | $1, $2, forward all: "$@", count: $# |
| Exit status of last command | $? (0 = success) |
| Test for a regular file | [ -f "$file" ] |
| Test directory | [ -d "$directory" ] |
| Compare numbers | [ "$a" -gt 10 ] (-eq -ne -lt -le -ge) |
| Compare strings | [ "$a" = "yes" ] |
| Read input | IFS= read -r name |
Ravindra Bagale's Tip
An interpreter error can come from a missing interpreter path or a script saved with CRLF line endings. Inspect the first line and convert a copy to LF if needed. Use bash -n for syntax and then test the intended invocation.
Ravindra Bagale's Tip – मराठी
Interpreter error आल्यास interpreter चा path आणि CRLF line endings तपासा. गरज असेल तर फाइलची प्रत LF मध्ये बदला. bash -n ने syntax तपासा आणि मग योग्य पद्धतीने script चालवा.
Ravindra Bagale's Tip – हिंदी
Interpreter error आए तो interpreter का path और CRLF line endings जाँचें। जरूरत हो तो फ़ाइल की प्रति LF में बदलें। bash -n से syntax जाँचें, फिर तय तरीके से script चलाएँ।
Lab
खालील workshop lab मध्ये report script योग्य input ने चालवा. मग चुकीची row वापरून status तपासा आणि cmp ने आधीचा report बदलला नाही हे पहा.
Turn a checked handover into a repeatable command
The Mauli workshop has a file with inspection results. The supervisor asks for a report showing the number of runs, the number that passed, and the number that failed. A student can read the four records and count them by hand today. Tomorrow the data can change, and someone else may need to repeat the computation. A shell script is a plain text file of shell instructions that can express the same steps, their expected inputs, and what should happen when a step fails.
Choose a small requirement before writing the script. The input in this exercise has a header with the words station and outcome. Each later line has one station label and one outcome, either passed or failed. The expected report for the initial data reads four runs, three passes, and one failure. At least one data row must be present. If an input file is missing, malformed, or empty, the script should report the problem and preserve the previous valid report. That last behavior is as important as the arithmetic. The people preparing to open the report depend on seeing valid results even if today's update cannot be produced.
The shell script uses Bash and ordinary file inspection commands. A command in a script can run another program such as awk, evaluate a test, or control which branch executes. The details matter at each step. A filename must preserve spaces. A writer must check whether its output is valid. The next action must depend on the outcome of the previous one. Keep the inputs and output named so you can review the behavior before anyone schedules it. This lesson uses a Bash shell and an isolated scratch path on Linux or another Unix-like practice machine with Bash available.
Prepare sample data and a previous good report
Begin in any terminal where you can run Bash. The setup creates a fresh directory and two files. The nested directory name includes a deliberate space so the test catches missing quotes around its paths. The previous report is a short stand-in for one that someone already trusts. You will preserve it until a new report passes the checks. This setup does not modify an actual deployment, a cron table, or your usual script directory.
script_lab=$(mktemp -d) || exit 1
printf 'Lab directory: %s\n' "$script_lab"
workshop_data="$script_lab/inspection runs"
mkdir "$workshop_data"
cat > "$workshop_data/results.txt" <<'DATA'
station outcome
press-a passed
press-b failed
press-c passed
press-a passed
DATA
printf 'Previous verified handover\n' > "$workshop_data/report.txt"
cat "$workshop_data/results.txt"
station outcome
press-a passed
press-b failed
press-c passed
press-a passed
The path printed before these lines is generated for your machine. All later commands use this same shell's variables. If you close the shell, start a new fixture or explicitly recover the scratch path you created. The quoted here-document marker tells the shell to copy those data lines literally. The output redirect chooses the path to create. The source and destination are different filenames. This example deliberately makes both expected input and previous output visible before developing the transformation.
Trace the data by hand. There are four data rows after the header. Press A contributes two passes, press C contributes one pass, and press B contributes one failure. The report can count runs by incrementing a variable for every valid data row. It can count passes and failures based on the second field. The final total should equal passes plus failures. A malformed row containing an unknown outcome should be identified instead of being quietly counted as zero. Each claim about the report can be checked with an independent small input.
Choose an interpreter and distinguish arguments from settings
The first line of a runnable shell file can name its interpreter with a shebang, a line starting with #!. The sample uses #!/bin/bash because its tests use Bash syntax and that path is available in the prepared lab. Calling bash script.sh explicitly also asks Bash to read it. Calling sh script.sh chooses the system's sh interpreter, which can handle a different subset of syntax. Write the script for the interpreter used by the normal invocation and test that same entry path. An executable bit is needed when invoking a local file directly as a program. Bash can read a non-executable script file given as an argument when its permissions allow reading.
Positional parameters are the arguments given to the script. $0 usually supplies the command or script name in this invocation, $1 is the first argument, and $# is their count. These values are different from the PATH and other environment settings the process receives. Our report accepts one positional argument: the directory containing the training files. Checking the count before reading $1 lets us explain the usage when a caller supplied nothing or too much. The next example demonstrates how to keep words with spaces together as separate arguments.
bash -c 'printf "count=%s\n" "$#"; for arg in "$@"; do printf "<%s>\n" "$arg"; done' \
demonstration "$workshop_data" 'opening shift'
count=2
</.../tmp.EXAMPLE/inspection runs>
<opening shift>
The first operand after the command text sets the new shell's name for this invocation. The next two are its positional arguments. Quotes on the outside preserve the generated directory as one argument. "$@" passes through the positional parameters one at a time, preserving the original boundaries, including spaces. Compare that with "$*" in Bash, which produces one joined value in this form. In an argument check, use the representation that matches what you intend. The unquoted form can also undergo splitting and pathname expansion, so it is unsuitable when forwarding exact paths.
Write a candidate and publish it only after validation
The script below validates its directory argument and input format, then builds a temporary report within the same directory as its intended output. It uses command status to decide which step follows. The previous report stays available while the new one is prepared. If a checked step fails, the script prints a diagnostic and exits with a category suitable for this lab. The input file is read only. Use it with the private directory created above, where no other process changes the input and output names.
cat > "$script_lab/workshop-report.sh" <<'SCRIPT'
#!/bin/bash
set -u
if [ "$#" -ne 1 ]; then
printf 'Usage: %s DIRECTORY\n' "$0" >&2
exit 2
fi
directory=$1
input=$directory/results.txt
output=$directory/report.txt
if [ ! -d "$directory" ] || [ ! -f "$input" ] || [ ! -r "$input" ]; then
printf 'Missing or unreadable results.txt in the requested directory\n' >&2
exit 2
fi
if [[ -L "$output" || ( -e "$output" && ! -f "$output" ) || "$input" -ef "$output" ]]; then
printf 'Report path must be a separate regular file or absent\n' >&2
exit 2
fi
candidate=''
cleanup() {
if [ -n "$candidate" ]; then
rm -f -- "$candidate"
fi
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
if ! candidate=$(mktemp "$directory/.report.XXXXXXXX"); then
printf 'Could not create a report candidate\n' >&2
exit 4
fi
if ! LC_ALL=C awk '
NR == 1 {
if (NF != 2 || $1 != "station" || $2 != "outcome") invalid++
next
}
NF != 2 || $2 !~ /^(passed|failed)$/ {
invalid++
next
}
{
runs++
if ($2 == "passed") passed++
else failed++
}
END {
if (invalid || !runs) exit 3
printf "Inspection runs: %d\nPassed: %d\nFailed: %d\n",
runs, passed + 0, failed + 0
}
' "$input" > "$candidate"; then
printf 'Could not generate a valid report. Check the input header and all outcomes.\n' >&2
exit 3
fi
if [ ! -s "$candidate" ]; then
printf 'Candidate report is empty\n' >&2
exit 3
fi
if ! mv -f -- "$candidate" "$output"; then
printf 'Could not publish the verified report\n' >&2
exit 4
fi
candidate=''
printf 'Wrote report: %s\n' "$output"
SCRIPT
bash -n "$script_lab/workshop-report.sh"
Read the script from the top. The argument count test accepts exactly one directory. set -u detects an accidental read of an undefined variable, so that explicit count check is important before asking for the first argument. The variable assignments stand on their own, with no spaces around the equal sign. The paths are quoted at their use sites, which protects the space deliberately present in the lab. -d asks whether the path is a directory, -f tests for a regular file, and -r checks readability in the process's context. When those checks fail, later actions cannot assume the input exists.
The output guard uses Bash's conditional syntax. It rejects an existing symbolic link, a path that exists and is not a regular file, and an output that already identifies the same object as the input. A literal string equality check would not catch two paths that are hard links to one file. The -ef comparison looks at identity metadata if both paths exist. These are practical guards for a private scratch directory where the script owns the inputs. A shared and concurrently writable directory can need stronger guarantees than check-then-use conditions. Do not run this training script against a public or unreviewed service directory.
The candidate variable is initialized before registering an exit trap. A trap tells Bash to run designated code when a named shell event occurs. The EXIT trap cleans a candidate when the script exits. The additional signal traps map ordinary interruption or termination requests to a shell exit, which lets the exit cleanup run. Some kinds of process termination cannot execute a trap. For a long-running job, use recognizable temporary names and a documented bounded retention process for leftovers. This script removes only the exact candidate it created and never targets a shared temporary directory as a whole.
The mktemp call creates the new file while selecting a unique path. Keeping it next to the destination avoids a cross-filesystem move for this fixture. The generated report goes to that candidate rather than opening the final report for truncation. After the report is ready, the successful same-directory rename gives readers of the final pathname a complete old or new file on a filesystem with ordinary rename semantics. A process already holding the old file open can continue to see its old contents. A rename is not by itself a lock, a history of older versions, or power-loss durability. Use stronger application-specific mechanisms where those guarantees are required.
Inside the awk program, the first record is the header. The first rule checks both field names and then skips it. The second rule rejects anything that does not match the expected pair of fields and outcomes. Every remaining row reaches the counting block. After the input has been read, the END block exits with status three if any invalid record occurred or no valid runs were counted. Only a fully accepted set reaches the aggregate print. For this known small file, the summary's counted runs should equal passes plus failures. Independent expected bytes in the next exercise verify that relationship against the command's output.
The shell treats the producer status as an explicit branch. An unsuccessful awk or output redirection triggers the diagnostic and exits before publication. The separate nonempty check is a final guard rather than the full semantic validation, which was performed by the awk program and tested on the fixture. If the move fails, the process leaves its previous valid output in place on the expected filesystem and the exit trap handles the candidate. If it succeeds, remove the now unused temporary pathname from the cleanup state before printing success. The order makes each status visible and easy to reason about.
Publication also replaces the file's identity and metadata. The candidate created by mktemp usually starts with owner-only access, subject to its rules and the current permission mask. The new report keeps the candidate's mode when it is renamed within the directory. That fits this private lab, and it might not fit a report that a different account must read. In an actual deployment inspect the mode and owner of the prepared file, test access under the intended reader, and apply only the documented permission requirements. An existing destination's permissions do not automatically become the new file's permissions after renaming.
For an additional validation, imagine the initial report says one failure and a second input has two. The two writers produce distinguishable complete content. During a failed second update the reader must still see one. During a successful second update it can see the old or new complete file depending on when it opens the final name. If the application's acceptance needs a precise version, store the source's identity with the report or use an agreed publication scheme. This distinguishes a valid snapshot from the newest intended snapshot. The lab's working directory has only one deliberate writer, and the exact comparisons check this step without requiring concurrency or changes to other files.
Test the success path and the paths that should fail
Start with the known valid input. Write the expected output independently, then run the script and compare the file. The exact output path includes the generated directory and varies by run. The final report lines should have the same order and content on a second run with the unchanged fixture. This tests what the caller can rely on, beyond a command returning zero or an output path existing.
printf '%s\n' 'Inspection runs: 4' 'Passed: 3' 'Failed: 1' > "$script_lab/expected.txt"
if bash "$script_lab/workshop-report.sh" "$workshop_data" \
&& cmp "$script_lab/expected.txt" "$workshop_data/report.txt"; then
cat "$workshop_data/report.txt"
else
printf 'The known result was not produced\n' >&2
fi
Inspection runs: 4
Passed: 3
Failed: 1
The script prints its output path before the displayed report. cmp compares bytes, including newlines. A match is normally silent, and a difference returns a nonzero status. The condition explicitly requires both a successful script and a match. If you change the spacing of the report by design, update the expected report only after deciding that the format change is intentional. If someone else consumes the file, document the expected form or use a format with a defined parser and validate semantics independently.
Now append a deliberately invalid line to the scratch input after saving the good one. The expected report should remain byte-for-byte equal to the previously verified report. Use a conditional branch to capture the expected failure, so this case works even if your terminal is set to exit on unhandled errors. When you restore the file, keep its verified content accessible for the final round of practice.
cp "$workshop_data/results.txt" "$script_lab/results.saved.txt"
printf '%s\n' 'press-d unknown' >> "$workshop_data/results.txt"
if bash "$script_lab/workshop-report.sh" "$workshop_data"; then
printf 'Unexpected success for malformed input\n'
else
printf 'malformed input status=%s\n' "$?"
fi
cmp "$script_lab/expected.txt" "$workshop_data/report.txt" \
&& printf 'Previous report preserved\n'
cp "$script_lab/results.saved.txt" "$workshop_data/results.txt"
malformed input status=3
Previous report preserved
The report script also writes its failure diagnostic, which may appear in a different order because it goes to stderr. The status line uses $? while the failure is still the most recent status. Do not put another command before that read. A match after the failure proves the old report was preserved. The important check is stronger than seeing an existing output name, because many scripts accidentally truncate a destination or publish a partial replacement even when their final status signals failure.
Try the missing-argument path using a separate invocation. Also check what happens if the entire input path goes away. The directory stays present, and only the disposable fixture's source is moved aside and restored. These cases should exercise argument and readability checks before creating any result. The file comparison afterward confirms that these caller errors did not change the published report.
if bash "$script_lab/workshop-report.sh"; then
printf 'Unexpected success without an argument\n'
else
printf 'missing argument status=%s\n' "$?"
fi
mv "$workshop_data/results.txt" "$workshop_data/results.temporary.txt"
if bash "$script_lab/workshop-report.sh" "$workshop_data"; then
printf 'Unexpected success without input\n'
else
printf 'missing input status=%s\n' "$?"
fi
mv "$workshop_data/results.temporary.txt" "$workshop_data/results.txt"
cmp "$script_lab/expected.txt" "$workshop_data/report.txt"
missing argument status=2
missing input status=2
There are separate usage and input diagnostics on stderr. These tests show that a successful syntax check does not guarantee correct behavior. They also illustrate why the script's argument handling is tested through its normal entry point rather than by manually retyping one or two internal instructions. When adding another supported option, test the combinations of existing and new arguments rather than assuming the count and order will still be correct.
Choose explicit shell status behavior
A script describes control flow. The command used in an if runs and the shell picks a branch based on its status. Tests such as [ "$#" -ne 1 ] return statuses too. The program's regular outputs travel through stdout and stderr independently of these decisions. set -u catches a particular class of undefined-variable mistakes. It does not cause the script to stop for every nonzero command. An optional setting can use a default expression when absence is expected. A required argument should be explicitly checked so the caller receives a useful diagnostic.
Similarly, set -o pipefail changes the combined status of pipelines in Bash, making an earlier failure detectable even when the last command succeeds. It does not tell the shell to exit immediately. set -e is a separate behavior with context-specific exceptions, including many test positions in conditional constructs. Automatic exit behavior is not a substitute for deciding which failures are expected and checking data when it matters. The report uses explicit conditions for the actions whose failure would prevent valid publication. It needs no pipeline in the production of its report.
Use this tiny model to see the distinction. The first stage is false, which returns nonzero. The second is an ordinary counter which successfully sees an empty input. With pipefail on, the pipeline returns a nonzero status. The next command in our subshell still executes, because no rule instructed the shell to exit on that status. The program reads the status immediately through an explicit conditional, then keeps going to finish the diagnosis.
(
set -o pipefail
if false | wc -l; then
printf 'Unexpected producer success\n'
else
printf 'pipeline status=%s\n' "$?"
fi
printf 'Finished the status test\n'
)
0
pipeline status=1
Finished the status test
The first display of zero is the count of newlines, with optional width padding. The number beside pipeline status is the shell's exit result for the chain. A valid but empty dataset can also give a zero count, so it is the next validation requirement that determines whether zero is acceptable. In stage composition a command can fail after writing partial output. Saving its result in a candidate and checking status helps avoid adopting a plausible but incomplete file.
Shell functions can keep one purpose in an easily identified unit. The cleanup function in the sample removes a known temporary candidate if that name is still present. It takes no positional argument because it uses state owned by this one script. A function that accepts inputs can use its own positional parameters and return a status just like another command. Avoid an unnecessary function when a test already states an operation directly. Choose a helper when it brings the variables and error handling for one task into a single place.
Preserve what belongs to one input while iterating
A script often repeats one operation for several inputs. A for loop can process a list of arguments, such as separate training paths. A while loop can process records read one at a time from a text stream. Decide what counts as one input before choosing the loop. For the report's fixed two-field format, awk already reads records and splits them under defined rules. A shell loop can still be useful when each whole line is an instruction or name to present verbatim. It needs to preserve spaces, backslashes, and known line boundaries.
Make an input with two station labels. The first includes leading and trailing spaces. The second includes a backslash and deliberately has no final newline. The loop below reads the lines while preserving these characters. The optional condition following read admits the final nonempty record even when the read ended because the input ran out before a newline. The print uses a constant format and a quoted argument, so a literal percent sign or whitespace in the line would remain data.
{
printf '%s\n' ' press a '
printf '%s' 'sensor\west'
} > "$script_lab/labels.txt"
line_count=0
while IFS= read -r label || [ -n "$label" ]; do
line_count=$((line_count + 1))
printf 'label %s: [%s]\n' "$line_count" "$label"
done < "$script_lab/labels.txt"
printf 'labels read: %s\n' "$line_count"
label 1: [ press a ]
label 2: [sensor\west]
labels read: 2
IFS names the shell's input field separators for several operations. Setting an empty value for this read avoids trimming or splitting the line. The -r flag keeps backslashes literal. The command substitution pattern for word in $(cat file) would instead use splitting and possibly wildcard matching in a normal unquoted context, which is unsuitable for whole labels. Use the loop form that fits the format. If input records are allowed to contain newlines within quoted values, such as general CSV, choose a parser for that format instead of assuming a line-reading loop understands it.
The input redirection at the end feeds the file into the loop itself. In Bash, wrapping the loop as the last stage of a pipeline normally runs it in a separate execution environment, subject to shell options and conditions. Assignments there may not reach the shell reading their values afterward. This fixture uses ordinary redirection so the count remains available for the final print. Even when you deliberately choose a different pipeline arrangement, confirm where the loop actually runs before relying on its variables after it exits.
Arithmetic expansion here evaluates the small integer expression and assigns its result. Use numeric tests for documented numbers and string comparisons for literal labels. For example, a caller can require a result count greater than zero using -gt, and can select a known mode with a string comparison. Validate numeric user data before feeding it into shell arithmetic. A literal comparison of two strings generally has no reason to interpret an expression. In the report generator awk owns the row counting and the enclosing Bash reads its status. That separation is part of the design.
Run the same script under the same conditions as its caller
When a script behaves differently on another machine, start by confirming how it was launched. Compare the shell path named by its shebang with the interpreter that actually ran it. A script written with Bash's [[ ]] syntax is not portable to every /bin/sh shell. If a scheduled job explicitly invokes sh, the shebang inside the file does not change the interpreter already selected by the caller. Use Bash explicitly where the script needs Bash, and test the launch path the job will use instead of only running its individual commands in a terminal.
Windows-style CRLF includes carriage return before line feed at the end of each line. A Unix-style shebang can then appear to name an interpreter with an extra carriage return. An error mentioning an interpreter can also mean that the real path named by the file does not exist. Inspect the first bytes with od -c or review the editor's line-ending setting rather than assuming the cause. Convert a copy to LF with an appropriate editor or reviewed tool and retest syntax and behavior. The original should remain available until the change is understood. The examples here generate Bash files with Unix newlines directly.
Check dependencies and expected context too. A reporting command may use awk, mktemp, and mv from the command search path. Your normal shell can have aliased or substituted versions. A minimal environment may find another version or miss a required tool. Read the version and feature assumptions before adopting the script across distributions. Explicit paths to input and output help control the filesystem context, while a suitable environment and account control what the process can actually read and write. The training file's space-containing directory catches one class of errors immediately.
If a script is launched as Linux EC2 user data, the image's supported initialization mechanism interprets that data. Typical user data shell scripts run on initial launch by default under the image's documented behavior, and customization can change the schedule. The execution account and environment can differ from your SSH session. Verify the actual startup log in an authorized disposable environment and never place real credentials in sample user data. The local report lab models a safe script and its explicit result, without needing to launch a cloud instance or alter any bootstrap configuration.
A shell trace such as Bash's -x prints expanded commands, which can expose data supplied through variables or arguments. In a disposable worksheet example you can choose what trace to capture. For a service with secrets, log the relevant decisions and statuses without printing expanded credentials. When diagnosing destructive behavior, inspect the script and replicate the narrow case using disposable files before rerunning. A failed test can be preserved as evidence of the current behavior and then rerun after a deliberate correction.
Give a review function one small contract
Once a report has been written, a teammate can use a separate function to compare it with the expected fixture. The function should distinguish a successful match, different readable files, and a comparison problem. That keeps it useful in a test script where the caller may want to run another independent test even if one result differs. Make the expected behavior small enough to explain before you add shell syntax. In this exercise the function only compares two paths. It does not regenerate the report or change either file.
(
compare_report() {
if [ "$#" -ne 2 ]; then
printf 'compare_report needs expected and actual paths\n' >&2
return 2
fi
local expected=$1 actual=$2 outcome
if cmp -s "$expected" "$actual"; then
printf 'review: expected bytes confirmed\n'
return 0
else
outcome=$?
fi
case "$outcome" in
1) printf 'review: file contents differ\n' >&2 ;;
*) printf 'review: comparison could not complete\n' >&2 ;;
esac
return "$outcome"
}
compare_report "$script_lab/expected.txt" "$workshop_data/report.txt"
printf 'Incorrect expectation\n' > "$script_lab/wrong-expected.txt"
if compare_report "$script_lab/wrong-expected.txt" "$workshop_data/report.txt"; then
printf 'Unexpected match\n'
else
printf 'review function status=%s\n' "$?"
fi
rm -- "$script_lab/wrong-expected.txt"
)
review: expected bytes confirmed
review: file contents differ
review function status=1
The order of stdout and stderr can vary in a combined display. The call with the correct file succeeds. The comparison with the intentionally wrong expectation reports a difference and returns one, so the caller's failure branch runs. The function's $1, $2, and $# refer to the arguments it received from the surrounding script. The local declaration limits its named variables to that call. Bash treats those declaration assignments as assignment values, and quoting is still needed when passing the resulting names to the comparator. The enclosing parentheses keep the demonstration function from becoming a definition in the student's normal shell.
The function uses return to send a status to its caller without ending the surrounding script. An exit there would end the enclosing shell execution in this scenario. That choice is part of the contract. A reusable comparator often reports its own result and lets the caller decide whether to stop the whole process. The generator is the top-level program, so rejecting its only input or failing to publish its only output can reasonably use exit. Even two similar checks can need different control flow depending on who is responsible for the next decision.
Read a case command as a selection between patterns. The literal one pattern matches the documented difference status, while the asterisk covers other outcomes. In this use the underlying comparison command distinguishes a difference from a problem opening or reading one file. If a test compares a missing path, the latter branch is expected. The message plus status is easy to interpret. When an external tool has different documented statuses on your platform, choose categories consistent with that tool and verify them using concrete good and bad inputs.
You can build a tiny test matrix from these cases. A valid report yields match. An intentionally wrong expectation yields difference. A missing expectation yields an error rather than meaningful content disagreement. Missing function arguments yield the function's own usage failure. Each check can be done without changing either actual report path. Running a comparison function is useful even when the report generator already validated its own input, because acceptance by a different reviewer supplies independent evidence about the artifact the caller received.
Finally, separate the instruction that reports success from the operation that creates evidence. A function can accidentally return a final printf status after its underlying operation fails. Here the case statement prints a message and the function deliberately returns the earlier stored comparison status. The generator similarly prints only after the publication command succeeds. Capturing the meaningful status before emitting human-readable output helps the next script make the correct decision. That is particularly important when connecting several small scripts through conditional calls.
Test safety claims with a controlled path error
A training report takes care to preserve its input and any previous output. You can test that promise under an unusual path arrangement without involving a live service. Create a distinct scratch directory for the test. Make a new input there and create a hard link named report.txt to that exact input object. The two path strings differ, and both succeed as regular file tests. Using an identity check is what lets the script detect the problem. The exercise only uses the new scratch paths and leaves the main report available.
alias_case="$script_lab/alias case"
mkdir "$alias_case"
cp "$script_lab/results.saved.txt" "$alias_case/results.txt"
ln "$alias_case/results.txt" "$alias_case/report.txt"
if bash "$script_lab/workshop-report.sh" "$alias_case"; then
printf 'Unexpected success on a shared input and output object\n'
else
printf 'shared file status=%s\n' "$?"
fi
cmp "$script_lab/results.saved.txt" "$alias_case/results.txt" \
&& printf 'Input bytes preserved in the alias test\n'
rm -- "$alias_case/results.txt" "$alias_case/report.txt"
rmdir -- "$alias_case"
unset alias_case
shared file status=2
Input bytes preserved in the alias test
The shell also captures a diagnostic naming the invalid output. The script did not need to open a temporary candidate because the guard rejected this setup first. A symbolic link in the output would trigger an earlier part of the same test. A regular separate report file is the only existing output accepted by the script. Even with these good guards, a hostile or concurrently writable destination needs stronger protection. In other work you can often avoid path races by operating in a directory controlled by the single task owner and using an established file publication API or reviewed lock for concurrent writes.
If two authorized jobs run at the same time in this private training model, unique candidate names prevent them from writing the same temporary file. Publication can still finish in a different order from job start. Both could produce a complete report, with the last successful publication becoming the one a later reader observes. Decide whether that fits the intended data freshness or whether a single writer, lock, or versioned output is necessary. A directory name is also not an input snapshot. A writer modifying the source during aggregation could yield inconsistent observations. Real workflows often prepare an immutable input for each run, then publish a named result for that input.
Separate file atomicity from broader consistency. Renaming one verified report gives a complete file at one pathname under the expected filesystem conditions. It does not put another file, remote database row, and outgoing notification into the same update. If a routine needs those operations to succeed together or be retried safely, specify its failure and recovery model before adding shell commands. The workbook example is intentionally one report in one directory, with expected bytes and a demonstrable failure behavior.
Build a short test record another student can repeat
For the first task, predict the totals after adding a valid failed row to the known source. The expected facts are five runs, three passes, and two failures. Save the original known input, change only the scratch file, then run the normal script and check the new report. Restore the original and rerun. A good record shows which input was used for each report and confirms that each failure count equals the expected relationship between total and pass. This gives a concrete test for a meaningful data change beyond the original fixed example.
For the second task, practice an empty valid-looking input. Replace the disposable input temporarily with only its expected header, then run the script and record status three. It should preserve the previously generated valid report, just like the malformed-row test. A missing input and an empty input may lead to similarly blank terminal output in an untested script, but they have different causes and different evidence here. Restore the saved fixture afterward. If your real report has a documented zero-run case, you would adjust its rules and add a test explicitly accepting that outcome.
For the third task, check the usage branch and the actual executable path. Run the prepared file through Bash, then set owner execute permission on just that scratch script and run it directly. The first-line interpreter makes the chosen implementation explicit in the direct case. Compare the two results and verify that they match the intended fixture. An error from the direct invocation can indicate missing executable permission or an interpreter problem. A successful manual command elsewhere says little about the invocation that actually failed.
A script review should make it possible to list all expected outputs and where they can be written. In this exercise the output replaces the known regular report only after validation, the temporary candidate stays in the same directory, and errors use stderr and an explicit status. The usage and input errors are two, invalid data or candidate content is three, and a problem creating or publishing a file is four. These numbers belong to the script's own documented contract. Users may also receive a shell or signal status under other conditions. Describe the expected categories rather than assuming the same values have the same meaning in every utility.
After the practice runs, confirm that the path printed during setup refers to this lesson. The command removes the explicit fixture files and empty directories. The cleanup does not use a recursive deletion or a wildcard. If a test was interrupted, list the known scratch directory and examine any unrecognized temporary file before deciding whether to remove it. Keep legitimate evidence of a failed run if you are reporting a defect in the exercise. If there is a choice between an unexplained broad deletion and leaving a known small directory in place for review, preserve the evidence.
if [ -n "${script_lab:-}" ] && [ -d "$script_lab" ]; then
printf 'Cleaning lesson fixtures in %s\n' "$script_lab"
rm -f -- "$workshop_data/results.txt" "$workshop_data/report.txt" \
"$workshop_data/results.temporary.txt" "$script_lab/workshop-report.sh" \
"$script_lab/results.saved.txt" "$script_lab/expected.txt" "$script_lab/labels.txt"
rmdir -- "$workshop_data" "$script_lab"
fi
unset script_lab workshop_data line_count label
Explain how the script earns its success message
Interview question. Why does the script write to a candidate first?
Opening the final output directly can truncate it before a valid result is available. A separately created candidate can be verified while the previous report remains readable. A successful same-directory rename can then replace the pathname with the complete new file. This protects one published artifact under the stated filesystem and ownership assumptions.
Interview question. Which problem does pipefail solve?
It changes Bash's combined pipeline status so a failure from an earlier stage can be represented even if the last stage succeeded. A nonzero status still needs to be handled according to its meaning. The application should independently validate report contents and a successful script should confirm the expected result.
Quiz. Why do we use "$@" when forwarding arguments?
It preserves the original argument boundaries, including spaces within one pathname. The environment and positional arguments are separate inputs. The first parameter check in the lab uses the number of arguments so a missing directory can produce a clear usage result.
Quiz. The malformed fixture produced status 3. What is the strongest evidence that the prior report survived?
Compare it byte for byte with the known expected report from the previous successful run. Its presence by itself would also be consistent with partial or empty output. Capture the explicit error and the result of the comparison together.
Quiz. A script succeeds when run through Bash and fails in a scheduled job that uses sh. What do you check?
Confirm which interpreter the job invokes and whether the script uses syntax specific to Bash. Match the documented entry point, then test with the job account, search path, and explicit file paths. A shebang can choose the interpreter for direct execution but does not change a separately invoked sh process.
Revision cards
Define the inputs and result
Document the interpreter, positional arguments, relevant environment, and report format. Include a small fixture with independently known results.
Handle expected failures directly
Inspect the important statuses. Keep prior results available until verification passes and direct diagnostics to the appropriate stream.
Test the normal entry point
Run valid, invalid, missing and unusual-path cases through the same script. Compare the result and any retained files after deliberate failures.