Ravindra BagaleCourses & study guides मराठी Track your progress

Chapter 4: Linux Advanced Commands

AWS Cloud

4.4 Pipes and redirection

In short: Pipes are like a relay race — the output of one runner (command) is handed to the next.

Friends, a pipe is a relay race. Pipes are like a relay race — the output of one runner (command) is handed to the next. Technically, the shell connects the standard output (stdout) of the left command to the standard input (stdin) of the right command. In other words, the output of one command becomes the input of the next. Once you master this, you can combine small commands into powerful one-liners.

Symbol Meaning Example
| (pipe) Connect left stdout to right stdin printf '%s\n' 'pass' 'fail' | grep -Fx fail
> Redirect output to file (overwrite) echo "hi" > a.txt
>> Append output to file date >> log.txt
< Take input from file cat < report.txt
2> Redirect errors cat review.txt 2> errors.txt
2>&1 Duplicate the current stdout destination onto stderr ./script.sh > out.log 2>&1
&> Output and errors together (bash) cmd &> all.log
/dev/null "Black hole" — discard cmd > /dev/null 2>&1
tee Copy stdin to a file and to stdout printf '%s\n' 'press-a' | tee saved.txt
&& / || Run next only if success / failure test -s report.txt && cat report.txt

Why sudo tee instead of sudo echo > file?

The running shell opens the destination named after a redirection. Elevating a command with sudo does not change the credentials of this shell. tee opens its output paths itself. Use the scratch directory shown below to study the same behavior without elevated permissions.

Here-documents (used a lot in this book)

A here-document supplies multiple lines to a command as standard input. A quoted opening delimiter preserves literal variable names in the body. Here, cat sends the input to stdout and the shell redirects it to a scratch file.

preview_dir=$(mktemp -d) || exit 1
cat > "$preview_dir/hello.txt" <<'EOF'
Line one
The characters $HOME stay literal.
EOF
cat "$preview_dir/hello.txt"
rm -- "$preview_dir/hello.txt"
rmdir -- "$preview_dir"

Copy-pasting here-docs

Paste the whole block at once, including the final EOF line. The closing EOF must be at the very start of the line with nothing after it.

Ravindra Bagale's Tip

When a command appears to succeed with an empty result, run each step on its own. Check the input, the diagnostics, and the result status before trusting the report.

Ravindra Bagale's Tip

First make the redirection work in a directory you can write to. If a redirection fails, find out which process opened the file and check that you chose the intended output path.

Lab

खालील workshop lab मध्ये stdout आणि stderr वेगवेगळ्या फाइलमध्ये ठेवा. मग tee ने मधल्या टप्प्यातल्या ओळी जतन करा आणि शेवटी मिळालेली मोजणी तपासा.

| connects stdout to the next command. > creates or truncates a file, while >> appends. 2>&1 copies stdout’s current destination onto stderr.

Follow the workshop data through a command

A quantity of raw measurements arrives at the Mauli workshop at the end of a shift. The supervisor wants the lines representing failed inspections along with any warnings about how the measurements were collected. A student prepares a command that filters the raw lines and saves the result. The report looks normal. Later, the student discovers a warning was displayed only on the terminal and never went into the report. This is a useful problem for learning the shell, because the commands may have behaved exactly as written. The missing detail was where each type of output went.

A stream is a sequence of bytes moving through an input or output channel. A shell process ordinarily starts with three numbered channels. Standard input, or stdin, is channel zero. Some programs read the data to process from this channel. Standard output, or stdout, is channel one. Well-behaved commands usually write their primary results there. Standard error, or stderr, is channel two. It normally carries diagnostic messages. A diagnostic explains something about running the command, such as a missing file, a rejected input row, or a permission problem. The stream name does not force a message to be an error. A command can send progress, warnings, and other commentary through channel two by design.

These numbers are called file descriptors. A descriptor is a process's handle for an open file, pipe, terminal, or another way to read or write data. The numbers belong to the process. In a terminal session without redirection, stdout and stderr often both reach the screen, so their separation is easy to miss. Stdin usually starts at the terminal too. When you type a command after the prompt, you are supplying text to the shell. Once the shell starts a program that reads stdin, that program can receive terminal input until it finishes. The shell can arrange a different input source before starting it.

A command can also accept data as arguments or open the filenames it receives as arguments. For example, in cat runs.txt, the word runs.txt tells cat to open that file. In cat < runs.txt, the shell opens the file for reading on stdin. Without a file argument, cat reads that input and writes the bytes on stdout. Both forms usually display the same data, but the work of opening the file belongs to different actors. An error in the first form is reported by cat. An error opening the second is reported by the shell, which usually never starts the intended command. An argument that looks like a filename does not automatically make a program read from standard input.

Use Bash in an ordinary Linux environment to follow the lab, either on your own existing machine or an EC2 Linux lab you already control. The examples use fabricated workshop rows and intentionally produce a few diagnostic messages. They require no network, package installation, or administrator permissions. Start with the following block. Keep the shell open so it remembers the variable holding your scratch directory. A randomly named directory keeps this exercise separate from a project folder, and the commands that follow quote every path derived from it.

flow_lab=$(mktemp -d) || exit 1
printf 'Lab directory: %s\n' "$flow_lab"
cat > "$flow_lab/inspection.txt" <<'ROWS'
station result
press-b passed
press-a failed
press-c passed
press-b failed
press-a failed
ROWS
cat "$flow_lab/inspection.txt"

The generated directory name varies. The inspection file has a header and five data rows. Think through the report before writing a pipeline. Failed inspections are the second, fourth, and fifth data rows. Press A failed twice and press B failed once. Press C does not appear in the failure counts. The separator in this particular lab is whitespace. Each line follows the same two-field pattern. The commands use those literal records, so the manually counted station values will remain a reliable check throughout the exercise.

Inspect a pipeline one connection at a time

Our first transformation selects failed rows and keeps only the station field. The second puts matching station names next to each other. The third counts them. A pipe is an operating-system connection through which one process can write bytes that another reads. In Bash, placing a vertical bar between commands connects the left command's stdout to the right command's stdin, subject to explicit redirections on either command. A long pipeline repeats that connection between each pair of neighbors.

awk '$2 == "failed" { print $1 }' "$flow_lab/inspection.txt"
awk '$2 == "failed" { print $1 }' "$flow_lab/inspection.txt" | LC_ALL=C sort
awk '$2 == "failed" { print $1 }' "$flow_lab/inspection.txt" | LC_ALL=C sort | uniq -c
press-a
press-b
press-a
press-a
press-a
press-b
      2 press-a
      1 press-b

The first three lines come from the first command, the following three from the second, and the counts from the third. The padding before each count depends on the implementation. The header has a second field called result, so it fails the equality check and produces nothing. At the intermediate boundary after awk there are exactly three station lines and they follow the input order. At the boundary after sort the two press A lines become adjacent. uniq -c counts adjacent repetitions. If you remove sort, the two press A occurrences are separated by press B. The result then contains three single-line groups even though a command ran successfully.

The commands ordinarily run concurrently. They exchange bytes through the pipe while each is running, although a particular program decides when to read or write. A sorting stage typically needs to read all its input before it can emit a complete ordered result. A line-reading filter may start outputting sooner. Several waiting commands in a pipeline do not by themselves prove that one is stuck. Check whether the input is complete, whether an upstream producer is still running, and whether the stage you are waiting for inherently needs the entire input.

Choose boundaries you can inspect independently. If counts differ from the anticipated report, first run only the command that selects inspection results. Ask whether it preserved enough data, whether it emits a newline after each station, and whether there are additional labels. Append sort once that stage is correct, then append uniq -c. You can also capture the intermediate station names with tee while forwarding the same bytes downstream, as the lab later demonstrates. Each technique helps you locate a format or ordering error before editing all stages at once.

The specific command you choose needs to read stdin. Here sort and uniq read stdin when they receive no file operands. If you add a filename to sort, it reads the named file and ignores the piped input unless you include an explicit stdin operand supported by that program. A more general mistake is sending plain text to a command that expects a filename as an argument. The pipe offers input bytes. It cannot fill an argument position or interpret the bytes as words on your behalf. Read the command's input contract before joining it to another command.

Output formatting is also part of that contract. A spreadsheet writer might quote fields and embed delimiters, and a logger can emit JSON objects rather than a simple station name. Each example here deliberately restricts its output to one station label per line. For long-term processing you would describe that interface so a later change to the producer does not silently invalidate the consumer. A command that looks compact is useful when its stages and assumptions remain easy to verify.

Create a file, append a record, or read existing data

A redirection tells the shell to arrange a different destination or source for a numbered descriptor. A bare greater-than sign targets stdout by default. The shell opens the path for writing. If the file already exists under ordinary settings it truncates it, which sets its existing length to zero. The next command writes bytes starting from an empty output file. Two greater-than signs instead open for appending, so new output is added at the end of existing data. Both forms usually create the file if it does not exist and the directory permits creation.

printf 'First review\n' > "$flow_lab/review.txt"
printf 'Second review\n' >> "$flow_lab/review.txt"
cat < "$flow_lab/review.txt"
printf 'Replacement review\n' > "$flow_lab/review.txt"
cat < "$flow_lab/review.txt"
First review
Second review
Replacement review

Read the outcome as two separate displays. The first cat reads two lines. The second cat runs after a deliberately truncating write and reads one line. Choose append for a growing journal where each row records a new event. Choose a replacement report when the requirement is a full view of the new input. An append made during a rerun can count old observations again downstream. If each row needs a unique event identity and a duplicate row would be a problem, a file-growing append command on its own cannot enforce that policy.

There is an important ordering detail. Prefer to produce a report in a new path and verify it before replacing a previous report, because the shell usually opens the redirection before launching the program. In this lab cat "$flow_lab/review.txt" > "$flow_lab/review.txt" would open the destination for truncation and then have nothing to read. Using two differently spelled paths can still point to the same file if either name is a link. Keep inputs and new outputs in unambiguous locations. You can check input size and compare a candidate with its source before you replace anything needed by others.

Even the absence of output can truncate the destination. false exits unsuccessfully without printing a report. The file still gets opened by the shell. Try this with a disposable name. The checks after false save its status and test whether the named file has no bytes. The empty file is proof of the open, while the status is proof of failure.

printf 'Previous data\n' > "$flow_lab/separate.txt"
false > "$flow_lab/separate.txt"
printf 'writer status=%s\n' "$?"
if [ ! -s "$flow_lab/separate.txt" ]; then
  printf 'separate.txt is empty\n'
fi
writer status=1
separate.txt is empty

These commands assume a fresh Bash with its ordinary interactive behavior. If your shell is configured to exit on failure, run this and later deliberate failures in a fresh Bash session with the usual defaults or place the command in an explicit status check. Bash's optional noclobber setting can prevent a simple greater-than redirect from truncating a regular file. If it is enabled, the shell reports the rejected redirection and the previous file stays intact. The exercise demonstrates what can happen under the default, and separate output names still make the workflow easier to review with either setting.

A less-than sign targets stdin by default. Try awk '$2 == "failed" {print $1}' < "$flow_lab/inspection.txt" to see the same three lines that the named input gave us. You can also redirect stdin from a different source on a particular stage of a pipeline. This is a deliberate choice for unusual compositions. When learning, trace the streams before mixing these instructions. A reader that opens a different file or has stdin explicitly redirected cannot receive the intended upstream bytes.

Choose a destination for results and diagnostics

Make a small producer to stand in for a real program that can output both report data and a warning. This shell script prints two lines of station names as training data and writes one diagnostic about an ignored demonstration row. Both messages are written with Bash's built-in printf. The file itself is a program because we pass it to Bash for execution. You do not need to change its permissions or give it an interpreter line at the top.

cat > "$flow_lab/collect.sh" <<'SCRIPT'
printf '%s\n' press-a press-b
printf '%s\n' 'warning: 1 demonstration row excluded' >&2
SCRIPT
bash "$flow_lab/collect.sh" > "$flow_lab/results.txt" 2> "$flow_lab/diagnostics.txt"
printf 'Results:\n'
cat "$flow_lab/results.txt"
printf 'Diagnostics:\n'
cat "$flow_lab/diagnostics.txt"
Results:
press-a
press-b
Diagnostics:
warning: 1 demonstration row excluded

In the script >&2 sends the second print's ordinary output to the current destination of descriptor two. From the caller's perspective the form 2> sends that stream to the diagnostic file. No space separates the descriptor number and the first greater-than sign. If you write 2 >, the number becomes an argument and the redirection defaults to stdout. The blank following 2> before the name is fine. The two explicit destinations preserve clean data for the next tool and keep the message available for the reviewer.

Now run the same script through a pipe. A normal pipe carries stdout, so the count program receives two lines. The warning remains on stderr. This example also redirects that warning to a known path so the two result channels are easy to inspect in order. wc -l counts newline characters from stdin. The producer prints one newline for each record. If a file format can contain records without a final newline, decide whether newline counting matches the report's definition of a row.

bash "$flow_lab/collect.sh" 2> "$flow_lab/pipe-diagnostics.txt" | wc -l
cat "$flow_lab/pipe-diagnostics.txt"
2
warning: 1 demonstration row excluded

There may be spaces before the display of two on systems that format the count with a width. If the warning were sent through the pipe as a third line, the count stage would report three newlines even though there are only two data records. This is why merging stderr into data intended for further parsing can change the report without any shell error. Join both streams only when the destination expects a mixed human-readable transcript or otherwise understands the format. You can append details about rejected rows to a separate audit file and present the two files together.

To capture both streams in one file, redirect stdout to the file first. Then use 2>&1 to duplicate stdout's current destination onto stderr. The ampersand marks descriptor duplication. Without it, 2>1 opens a file called 1 as the destination for diagnostics. Both forms make sense to Bash, which is why a missing character can create a surprising file without causing a syntax error. The stream names in this example are descriptive, but the numeric behavior is what makes the redirect work.

bash "$flow_lab/collect.sh" > "$flow_lab/combined.txt" 2>&1
cat "$flow_lab/combined.txt"
press-a
press-b
warning: 1 demonstration row excluded

Bash processes multiple redirections from left to right. Think of 2>&1 as copying the destination held by channel one at that moment. It does not create a lasting link that changes whenever a later redirect changes stdout. Trace both sequences from the starting terminal setup. In the correctly ordered line above, stdout first goes to the file. Stderr then points to the same opened destination. In the reversed sequence below, stderr first gets the original terminal destination. The later redirect sends only stdout to the file. To make that original destination predictable, the outer subshell sends its own stdout to a separate fixture before the inner command applies its redirections.

(
  bash "$flow_lab/collect.sh" 2>&1 > "$flow_lab/reversed-data.txt"
) > "$flow_lab/previous-stdout.txt"
printf 'Final stdout destination:\n'
cat "$flow_lab/reversed-data.txt"
printf 'Previous stdout destination:\n'
cat "$flow_lab/previous-stdout.txt"
Final stdout destination:
press-a
press-b
Previous stdout destination:
warning: 1 demonstration row excluded

The parentheses run the inner list in a subshell, a separate shell environment that starts with the outer output redirection. Read the example from the outside in. Before the collector starts, stdout already points at previous-stdout.txt. Next, the collector's descriptor two copies that destination. Finally descriptor one switches to reversed-data.txt. This isolates the order without relying on whatever drew your terminal screen. The order matters whenever you redirect to a file, a terminal, a pipe, or a combination of those destinations.

Opening the same path twice is a different operation. If you write > transcript.txt 2> transcript.txt, there are two separate open operations. Both descriptors have their own position in the file, so data written through one can overwrite bytes written through the other. The duplication form starts from a single open file description and shares its current position. That is the practical reason to duplicate a destination instead of repeating its path. Even with a shared destination, the order of messages from a real program can reflect buffering, meaning that a program may accumulate text before actually writing it. The small collector prints each line directly, so it is suitable for learning the redirection order.

Bash offers &> file as shorthand for > file 2>&1. It also has |& to pipe stdout and stderr. In Bash the implicit stderr redirect from |& happens after any explicit redirects written on the left command. Mixing forms without tracing their order can produce something different from the apparent intent. For a shell script expected to run with POSIX sh, use explicit standard forms instead of assuming Bash-specific syntax. In this lesson the shell is Bash and the basic descriptors transfer across shells.

/dev/null is a special device on Linux. When you write data there, the device discards it. In a predictable maintenance command you may want to suppress a known noisy report stream and keep diagnostics, using > /dev/null. During a first test it is usually more informative to keep stderr and look at it. Redirecting both streams to this device can leave the same status for failure with no message to explain it. /dev/null also gives immediate end of input when used for reading, which is a separate purpose from throwing away output.

Save an intermediate result with tee

The supervisor may want both the tally and the exact selected station names for auditing. A command with a file redirection can put the names in that file. An ordinary pipe alone forwards the names to the tally. tee accepts bytes on stdin and copies them both to its own stdout and to the paths you provide. It gives you an explicit place in the pipeline where you can collect evidence while still handing the same records to the following stages.

awk '$2 == "failed" { print $1 }' "$flow_lab/inspection.txt" \
  | tee "$flow_lab/selected.txt" \
  | LC_ALL=C sort \
  | uniq -c > "$flow_lab/tally.txt"
printf 'Selected rows, in arrival order:\n'
cat "$flow_lab/selected.txt"
printf 'Grouped tally:\n'
cat "$flow_lab/tally.txt"
Selected rows, in arrival order:
press-a
press-b
press-a
Grouped tally:
      2 press-a
      1 press-b

Notice where the copies were taken. The selected file preserves arrival order because tee is before sort. The tally file receives the final counts because it is at the end. If you move tee after sort, that saved copy has sorted rows instead. If you move it after uniq, the saved file holds totals and loses the ability to recreate the original row order. The same command supports several goals, while the placement of tee determines which bytes you can inspect later.

The default destination will be replaced by tee on a repeat run. Add -a to append when each invocation is deliberately recording a new event. In a workshop handover you usually want the selected file to describe the same inputs as the one tally beside it. Using append for one and replacement for the other can create records that no longer agree. This is a meaningful behavior choice even when both files contain valid text. If a failed pipeline leaves just part of a report behind, handle the run status before allowing others to use the output.

You may see elevated writing through sudo tee elsewhere. Elevating a command with sudo does not elevate a redirection performed by your current shell. If you run an elevated program with a greater-than sign after it, the current shell still needs permission to open the output path. With tee, opening the destination is part of tee's work, so the credentials under which tee runs determine the file access. That explains the permission difference. This lab stays in a private user-writable directory. When a privileged config file really must change, follow the reviewed service-specific change and rollback procedure for the machine you manage.

Distinguish a valid report, a command status, and stage statuses

The shell tracks a small integer exit status when a command finishes. Zero indicates success according to that command. A nonzero value indicates another outcome such as failure or an ordinary condition defined by the tool. The shell stores the most recent command or pipeline status in $?. Commands do not communicate exit status by printing a number. A failed command can print a message including a zero, and a successful one can emit nothing. Read the rule for the particular command before deciding whether a status requires another action.

A Bash pipeline normally uses the status of its last stage. Suppose the input path has a typo and cat cannot read it. The counting command receives no rows, reports zero, and succeeds in counting what it received. The printed count and last command status together still provide no evidence that the source was opened. The next block triggers exactly that condition with a known missing file in the lab directory. Both runs intentionally count an empty stream. Read the messages and each stage's status before choosing whether to publish a report.

(
  set +o pipefail
  cat "$flow_lab/missing-input.txt" 2> "$flow_lab/read-error.txt" | wc -l
  printf 'default status=%s stages=%s\n' "$?" "${PIPESTATUS[*]}"
  set -o pipefail
  cat "$flow_lab/missing-input.txt" 2> "$flow_lab/read-error.txt" | wc -l
  printf 'pipefail status=%s stages=%s\n' "$?" "${PIPESTATUS[*]}"
)
cat "$flow_lab/read-error.txt"
0
default status=0 stages=1 0
0
pipefail status=1 stages=1 0
cat: .../missing-input.txt: No such file or directory

The exact path and diagnostic wording vary. The two zeros printed on their own are data produced by wc. The stage statuses are one from cat and zero from wc, in that order. PIPESTATUS is a Bash array holding the stages' latest statuses. Its values, like the value of $?, can change when you run another command. Both expansions in the format command happen before printf itself runs, so the same print sees both views of the pipeline. The parentheses confine the option setting and changes to it to this small example.

Enabling pipefail changes the pipeline's combined status. Bash selects the value of the rightmost command that returned a nonzero status, or zero when every stage succeeded. It does not report the number of failing stages or tell you which stage failed. Decode the individual statuses and diagnostics to find a cause. You can explicitly test the pipeline before handing the report to another program. With the default settings an unavailable source and a readable empty source both appear to succeed, so a report should have an explicit rule for each case.

Even with pipefail, wrong data can look successful. Try the same station report from earlier without sorting. The producer, copy, and counting stages can each finish with status zero. The final result still fails the question about total failures per station, because identical stations in separate runs must be counted together. Add a known input and exact result check to the lab. A real report could also check duplicate groups, ensure source time ranges are correct, and require that the total of groups matches the number of selected rows. These are content checks that no shell option can infer.

Sometimes a reader exits early by design. A program such as head may read the requested amount and close the pipe. If a producer keeps writing after the reader is gone, the operating system can deliver a broken pipe signal. That upstream nonzero status can appear with pipefail. It may be expected in a pipeline intended as a preview, while the same status in a complete export deserves investigation. Do not suppress every nonzero status on the grounds that one preview uses early termination. Decide which byte range the pipeline must deliver and check statuses based on that purpose.

At a similar boundary, grep distinguishes finding a match, finding none, and failing to search. A filter designed to produce an empty report for zero failures must handle the no-match result as a valid branch, while an unreadable file needs its own decision. A training filter that has an ordinary zero-match outcome still needs an input check. This distinction is important when combining tools that use status one differently, such as an error from cat, no match from grep, and a difference from diff.

Guard the next action with an explicit check

The double ampersand and double vertical bar decide whether another command should run using status. They do not feed text from one command to the next. With first && second, the shell runs second when first succeeded. With first || second, it runs second when first was nonzero. For instance, use test with -s to determine whether the candidate tally has a size greater than zero before displaying a review message. Here that property is a necessary condition for this fixture's expected failures.

test -s "$flow_lab/tally.txt" && printf 'candidate contains bytes\n'
test -s "$flow_lab/missing-input.txt" || printf 'candidate unavailable\n'
candidate contains bytes
candidate unavailable

The test command reports its result through status. No byte of the tally is passed to printf. A candidate tally could still contain incorrect bytes, so verify content and provenance in a separate step. Where there are two meaningful actions for success and failure, write an if with clear branches. A short list such as check && process || recover also runs recover if process itself fails. That can be intentional, but it differs from treating recover as the exclusive alternative to passing the check. Writing the branches explicitly makes it clear how to handle each possible failure.

For a practical review on the complete fixture, run the pipeline with scoped pipefail and save its output to a candidate. This example only creates a normalized tally and a diagnostic file. The final awk formats the two fields from uniq so that the comparison does not depend on how the count is padded. A normal candidate is still just a candidate until it is compared with the expected lines. This also gives the class a repeatable regression check if the command is edited later.

printf '%s\n' '2 press-a' '1 press-b' > "$flow_lab/expected-tally.txt"
if (
  set -o pipefail
  awk '$2 == "failed" { print $1 }' "$flow_lab/inspection.txt" \
    | LC_ALL=C sort | uniq -c | awk '{ print $1, $2 }'
) > "$flow_lab/checked-tally.txt" 2> "$flow_lab/audit-diagnostics.txt"; then
  if cmp -s "$flow_lab/expected-tally.txt" "$flow_lab/checked-tally.txt"; then
    printf 'Verified training tally\n'
  else
    printf 'Tally differs or could not be compared\n' >&2
  fi
else
  printf 'Pipeline failed. Read audit-diagnostics.txt\n' >&2
fi
cat "$flow_lab/checked-tally.txt"
Verified training tally
2 press-a
1 press-b

The comparison is byte-for-byte and silent because of -s. The expected report is independent of the pipeline and follows the hand count. Check the contents of audit-diagnostics.txt after the run. For these inputs the diagnostics should be empty. An empty diagnostic file does not by itself prove a match, which is why the comparison is also required. On an error, the shell may have already created the candidate. The existence of that path is weak evidence of completion and makes it worth retaining separate status and content checks.

Give a command exact multiline input

The supervisor's training memo should include a placeholder reading $HOME so each student can see the variable name in writing. Re-entering a separate print command for every line is unnecessary. A here-document is part of shell syntax that feeds an inline block to the standard input of a command. We used it earlier when constructing the raw fixture and collector script. The command receiving the block decides what to do with it. In the next example cat writes it to stdout, and the greater-than redirection chooses the destination file for that stdout. The here-document alone does not choose a destination file.

writer=review-team
cat > "$flow_lab/memo.txt" <<'MEMO'
Workshop handover
Place the report in $HOME after review.
Prepared by $writer.
MEMO
cat "$flow_lab/memo.txt"
Workshop handover
Place the report in $HOME after review.
Prepared by $writer.

Because the opening delimiter is quoted, the body is used without variable expansion. The closing delimiter is written exactly as MEMO, without quote characters, additional spaces, or other text. The first line after the introducer starts the data and the closing delimiter ends it. If the shell keeps showing a continuation prompt instead of running the command, check for a missing or indented terminator. Cancel the unfinished command using Control C and run the complete block. For ordinary << use the left margin. Bash's <<- variant strips leading tab characters, which are different bytes from spaces.

If the opening delimiter is unquoted, Bash performs parameter, command, and arithmetic expansion on the body subject to the here-document rules. That can be appropriate when you deliberately generate a memo with a known label. It can be surprising when taking a literal script or config copied from documentation. The next block expands the variable named writer, and the literal sample above preserves its name. Compare the two files so you can explain whether the edit happened before cat received the bytes or while cat was running.

cat > "$flow_lab/memo-personal.txt" <<MEMO
Workshop handover
Prepared by $writer.
MEMO
cat "$flow_lab/memo-personal.txt"
Workshop handover
Prepared by review-team.

Choose a delimiter that cannot appear by itself on a line of the desired body. If you use a command inside a here-document as its text, the receiving program can interpret that text as its own syntax. Feeding the words to cat produces a file or display. Feeding those same words to a command interpreter can execute instructions. In a training lab, choose a receiver and a source you understand. Review copied blocks and keep the quoted delimiter if the body should stay literal.

Trace, test, and explain a complete handover

For a practical exercise, keep the original inspection file and add two rows to a new training copy. Use one pass for press A and one failure for press C. Predict four selected rows in the order A, B, A, C and a sorted count of two for A, one for B, and one for C. Run the report with the training copy as its input. Write down the three paths used for original data, selected rows, and counts. A reader should be able to recreate the report by tracing each path and understanding which stage creates it.

Next, make the pipeline's reading stage use a missing fixture name in this scratch directory. Run a diagnostic version so stderr goes to a separate file and use pipefail inside parentheses. The combined status should be nonzero because the source does not exist. If you had already created an output name via redirection, it might still be present with zero bytes. Inspect both files and explain which part of the result came from the shell before the pipeline ran. Use the known input path again to confirm the good case remains valid after the negative case.

Then add a diagnostic message to the separate collector's stderr in the scratch directory and run it again through the count example. The message should be present in the diagnostic file and the count should remain two. Redirect descriptor two into the pipe on a second run and check that the output would now include diagnostics. This shows concretely why choosing the correct descriptor is as important to output accuracy as choosing the correct awk field. Preserve the original stdout-only count for the handover.

If a command waits at the terminal, check whether it was given a file or a working producer. Some utilities wait for input until they receive an end-of-file indication. If a pipeline output includes an explanatory banner that you did not expect, run the producer by itself and observe its stdout and stderr separately. A banner sent to stdout becomes part of the primary stream unless the tool offers an output mode without it. If a file has no content after a redirect, check whether your command actually wrote to stdout, whether it failed before writing, and whether the destination matched the input unintentionally. Those are different problems that can leave the same visible symptom.

If a permissions message comes from the shell while trying to create a candidate, check the output path and your directory access. Once a command is given a destination it can also fail while writing, for instance when the storage becomes full. Treat the resulting output as possibly partial and keep the diagnostic. A successfully opened file path by itself tells little about whether all intended bytes arrived. For a routine report, include the expected row pattern and station sums, and make a final size or equality check appropriate to the task.

When you finish, display the generated path again and verify that it is the scratch directory from this lesson. The cleanup removes only known names. If you created extra exercise files, inspect the directory and remove those specific additions separately if you no longer need them. There are no cloud resources or system configurations to roll back.

if [ -n "${flow_lab:-}" ] && [ -d "$flow_lab" ]; then
  printf 'Cleaning fixtures in %s\n' "$flow_lab"
  rm -- "$flow_lab/inspection.txt" "$flow_lab/review.txt" "$flow_lab/separate.txt" \
    "$flow_lab/collect.sh" "$flow_lab/results.txt" "$flow_lab/diagnostics.txt" \
    "$flow_lab/pipe-diagnostics.txt" "$flow_lab/combined.txt" \
    "$flow_lab/reversed-data.txt" "$flow_lab/previous-stdout.txt" \
    "$flow_lab/selected.txt" "$flow_lab/tally.txt" "$flow_lab/read-error.txt" \
    "$flow_lab/expected-tally.txt" "$flow_lab/checked-tally.txt" \
    "$flow_lab/audit-diagnostics.txt" "$flow_lab/memo.txt" "$flow_lab/memo-personal.txt"
  rmdir -- "$flow_lab"
fi

Check your reasoning

Interview question. Trace all three descriptors for the collector with one diagnostic file and a count pipeline.

The collector receives its usual stdin, which the example script does not read. Its stdout flows through the pipe to the stdin of the counting command. Its stderr is independently opened on the diagnostic file. The count command's stdout still goes to the terminal. From two emitted station rows it prints a newline count of two, while one diagnostic line appears in the separate file. Start your explanation with the producer's streams and follow them through each shell operator.

Interview question. Does a pipeline run its last command after the earlier command produces a successful result?

The shell starts the stages so they can operate concurrently through pipes. A downstream tool often needs the bytes written by the stage before it, but can wait for those bytes while already running. An exit status is obtained after a command finishes. In the missing-input example the reader produced no output and the rightmost counter still executed. A conditional action using the double ampersand is how to express the requirement that a separate command's status gates the next action.

Quiz. Which redirect creates a mixed transcript in one reusable file?

Redirect standard output to the transcript path first, then use 2>&1 to copy that destination onto standard error. With the order reversed, standard error keeps stdout's previous destination. Writing 2>1 creates a different path named one, so the ampersand is an important part of the operator. Compare with the lab's two files when explaining the order aloud.

Quiz. All stages returned zero. The tally shows two distinct lines for press A. Which assumption failed?

Uniq sees adjacent runs. The station identities appeared in separate positions because the data was not sorted or otherwise grouped beforehand. Sort using a predictable ordering, or select a grouping tool that uses keys across all input. Check the normalized tally against independently counted values. Filtering and counting can each succeed while the report still answers a different question.

Quiz. A candidate path exists after a failed run. What evidence is still needed?

The shell can create that path in preparation for the command even when the writer later fails. Check the pipeline status and stage diagnostics, then validate the contents against known evidence or a required format. The original report should remain available while doing this. If an intentionally empty report is valid, verify the input was readable and selected no rows, because a failure might also create an empty candidate.

Revision cards

Three routes through a program

Descriptor zero is input, one is primary output, and two is diagnostics. A pipeline normally connects only one to the next zero. Keep machine-readable results and unrelated diagnostic lines separate.

Order decides where a copied descriptor points

A descriptor duplication uses the destination held at that step. Update stdout first if stderr should copy the new file destination. Trace left to right before you launch the command.

Verify two kinds of success

Use exit statuses to check execution. Use independent row counts, known outputs, or another semantic test to check meaning. The report should pass both checks before another person relies on it.

Primary references