Popular Searches

Decide Which Downloads Need Repair

ShellBeginner
Practice Now

Introduction

Field Notes is preparing a community weekend. Its resource pack includes a PDF guide, handouts and an optional empty credits file. A filename and plausible size are not enough to show that a download is complete. Before fetching anything, you will produce an inventory that tells the organizer which exact members need attention.

You should know basic Bash arguments, conditions and loops from Shell for Beginners. This lab explains SHA256, line-safe reads and the parsing used here. Tools and original synthetic resources are prepared. WebIDE, Workspace and Download Desk share one container; this lab starts independently. The time is an author estimate including reading, editing and ordinary typing errors.

Build a Trustworthy Inventory

In this step, you will turn a trusted checklist into an inventory of the actual local pack, without repairing or rewriting any pack member.

See the useful file first

Start in Workspace, which is prepared for UTF-8 text. Your work belongs in /home/labex/project/download-desk. pwd shows the current directory. If a relative path is missing, check it with ls and return here with the complete cd command.

cd /home/labex/project/download-desk
ls pack

Switch to Download Desk. Select Open file beside Welcome guide.pdf. The new browser page should show the community schedule and the east-entrance meeting point. Use the browser's PDF zoom controls if necessary; a PDF has fixed pages rather than a reflowing mobile layout. Return to the Download Desk page and select Download beside that file to save the same local bytes. Then switch back to Workspace.

Download Desk with links to the actual local resources

Use Open file or Download beside Welcome guide.pdf.

This reader only serves actual files in pack. It cannot retrieve a missing member from the source. A text resource may open as text and the optional empty file may show a blank page. Those observations alone do not establish correctness.

Use an independent reference

The organizer supplied /opt/labex/download-pack-state/expected.sha256 separately from the writable pack. A SHA256 digest is a 64-character fingerprint of file bytes. Comparing it with an independently trusted value detects different bytes, including same-size damage. It does not establish a publisher's identity: if an attacker supplies both a file and its checksum, agreement does not make that publisher trustworthy. Do not regenerate this reference from the files you are checking.

cat displays a file without changing it:

cat /opt/labex/download-pack-state/expected.sha256

Each line contains a lowercase 64-character digest, two spaces, then the complete filename. This course uses a provided, readable, nonempty, newline-terminated manifest in that exact format. Names are flat printable ASCII names and may include spaces. Slash, backslash, CR, LF, tabs, . and .. names are outside the scope. The pack and its directory chain are real directories; listed members are regular local files or absent. Linked files, subdirectories at a listed name and arbitrary escaped checksum formats are not supported. Keep every original pack member and notes.txt unchanged in this diagnostic lab.

sha256sum prints a file's digest and name. Double quotes keep the name containing spaces together. -- ends command options. The directory prefix also prevents a basename starting with - from becoming an option.

Start with a normal member whose PDF you have already opened. Compare this digest with the independent Welcome guide.pdf manifest line:

sha256sum -- "pack/Welcome guide.pdf"

They match. The command computes the digest of the actual local file rather than trusting its filename or preview. Now compare the damaged handout:

sha256sum -- "pack/Workshop card.txt"

Compare that digest with its reference line. They differ. The damaged file has the same number of bytes as the correct handout, so its size would not have exposed this mistake.

sha256sum --check reads the manifest and checks its listed paths relative to the current directory. Parentheses run commands in a subshell: its cd does not change your outer terminal's directory.

(cd pack && sha256sum --check /opt/labex/download-pack-state/expected.sha256)

Here && runs the check only if entering pack succeeds. Expect Welcome guide.pdf: OK, Workshop card.txt: FAILED, Map notes.txt: FAILED open or read, and Optional credits.txt: OK, plus warnings. The missing member and wrong bytes make this command intentionally fail. $? holds the previous command's native exit status; read it immediately, before another command replaces it. printf formats the value, and \n ends the line.

printf 'Check exit: %s\n' "$?"

Expect Check exit: 1. The zero-byte credits file is valid because its digest matches. “Nonempty” is a requirement for the manifest, not every resource. Seeing one OK line does not make the whole pack correct.

Read the manifest before building the loop

The organizer needs one status and one complete filename per row, in manifest order. Before writing code, predict the four rows from your observations: which file is missing, which has different bytes, and which two already match? An empty matching resource belongs in the last group.

You will create inventory.sh in WebIDE, then run it in Workspace. These tabs share the same files. Saving in the editor changes the program; running it in the terminal executes the saved version. The script receives the manifest as $1 and the pack directory as $2. It must work alone with those arguments and installed commands, without neighboring helpers.

Switch to WebIDE. Choose File → Open Folder, enter /home/labex/project/download-desk/, and confirm the folder. Wait until the Explorer shows DOWNLOAD-DESK. Choose File → New Text File. After typing the starting shell below, choose File → Save; in Save As, enter inventory.sh in this folder and confirm. The saved file should appear in the Explorer and its editor tab. Use File → Save after each edit (or the shortcut displayed by your editor). Auto Save may also be enabled; save explicitly before switching to Workspace. To locate a numbered line, press Ctrl+G, enter the line number, and press Enter. Click inside the code editor before typing; indentation added by the editor does not change the Bash logic.

In the new file, type this small starting shell. The first line names Bash; we will invoke it explicitly with bash, so no executable-permission change is needed. The assignments name the two arguments; they do not classify anything yet.

#!/usr/bin/env bash
manifest=$1
pack=$2

The Explorer and editor tab should identify the saved file as shown below. The three starting lines only name the program and its arguments.

Saved inventory file in WebIDE

Parse one whole line at a time

Read one trusted manifest line again. Its first 64 characters are the digest; the next two are spaces; everything after those separators is one filename. Splitting that line at every space would break Workshop card.txt into words.

  • while IFS= read -r line reads complete lines. Empty IFS prevents trimming spaces, and -r prevents backslash processing.
  • done < "$manifest" supplies the manifest as the loop's input. Without that redirection, read would wait for terminal input.
  • ${line:0:64} takes characters 0 through 63; ${line:66} keeps the complete filename after the two spaces.
  • target=$pack/$name joins the selected directory and basename. Quote "$target" when passing that path to commands.
  • printf '%s\t%s\n' prints two values with a tab between them and a newline after each row.

After pack=$2, type the following first version of the loop. status=MISSING is a provisional default; it is not a claim that every member is absent.

while IFS= read -r line; do
    expected=${line:0:64}
    name=${line:66}
    target=$pack/$name
    status=MISSING
    printf '%s\t%s\n' "$status" "$name"
done < "$manifest"

Read this partial version in the editor before adding the next decision. If it ran now, all four complete names would be printed as MISSING: it never examines a file. That prediction explains the limitation of the current lines; do not execute the incomplete version or create a report yet. You will run the completed classifier after both decisions are implemented.

Separate absence from present bytes

Return to WebIDE. Locate status=MISSING. The next decision belongs immediately after that assignment and before printf, still inside the while loop. [ -f "$target" ] asks whether the supported target is a regular file. An absent member should keep the existing default without invoking a checksum command.

actual=$(sha256sum -- "$target") captures command output. ${actual%% *} removes the longest trailing part matching a space followed by anything, leaving only the digest. This uses the controlled filename format explained above.

Add this local branch at that position:

    if [ -f "$target" ]; then
        actual=$(sha256sum -- "$target")
        actual=${actual%% *}
        status=MISMATCH
    fi

Read the modified lines before running them. Which resource must still say MISSING? Why will even the correct PDF now say MISMATCH? This version recognizes presence and computes its digest, but has not compared that digest with expected.

Keep this as a reading prediction rather than executing the partial program: the absent map would remain MISSING, while all three present members would say MISMATCH. The zero-byte resource is present too. Finish the equality decision next before saving and running the completed classifier.

Let equality select MATCH

Return to WebIDE. Inside the file-exists branch, locate status=MISMATCH. A present file starts in that state; it may become MATCH only when its actual digest equals the trusted one. Write a nested Bash if immediately after that assignment and before the branch's closing fi. Use [ "$actual" = "$expected" ] as its test, assign status=MATCH in its successful branch, and close the nested branch with its own fi. No else is needed: unequal values keep MISMATCH.

Check the nesting before saving. There are two if tests and two corresponding fi lines, followed by the existing printf; done still closes the manifest loop. Predict all four final statuses before running.

Save and return to Workspace. Now run the completed classifier. > redirects standard output into inventory.tsv, replacing the report on each run. TSV means tab-separated values; this report is separate from the pack, so no resource is rewritten:

bash inventory.sh /opt/labex/download-pack-state/expected.sha256 pack > inventory.tsv
cat inventory.tsv

Expect these rows, with a tab between status and complete filename:

MATCH Welcome guide.pdf
MISMATCH Workshop card.txt
MISSING Map notes.txt
MATCH Optional credits.txt

The script may exit zero while reporting MISSING: its job is classification, not a claim that the pack is complete. A fixed list of these four rows would not be a reusable classifier. The check runs your saved script against different names and changed current files, including an empty member; equivalent loops are accepted.

Correct a saved mistake without resetting the pack

If Bash reports a syntax error, keep the message and its line number. In WebIDE, open inventory.sh, locate that line, and inspect the preceding if/fi or while/done pair as well. For example, fii is a misspelling of fi; adding a second complete script below the old one would not repair that mistake. Change the offending characters in place and save. Switch to Workspace and rerun the report command, then read the resulting rows.

If the program waits without returning, press Ctrl+C in Workspace and check that done < "$manifest" is intact. If a relative path is missing, use pwd, ls and the complete cd shown at the start. These recoveries change the script or invocation, never the pack or trusted reference.

Run the completed inventory once more and compare the rows:

bash inventory.sh /opt/labex/download-pack-state/expected.sha256 pack > inventory.tsv
cat inventory.tsv

They should be identical because this program only reads the pack. Leave all original members and notes.txt unchanged. In the next lab these classifications will decide which resources need a request.

Summary

You opened a real resource, compared its pack with an independent SHA256 reference, and built a line-safe Bash inventory. You separated missing members, wrong bytes and matching empty files while preserving the original pack. The inventory now supplies a reason for each later repair.