Linux Foundations / Predict What the Shell Does

Redirect output and errors deliberately

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

A command can print useful results and report a problem during the same run. Saving everything you see on the terminal is different from choosing which kind of output belongs in a report. A missing result may mean that the command failed, that you sent its output elsewhere, or that it had nothing to print. You need evidence to distinguish those cases.

In this lesson you will keep a small input unchanged, collect a listing and its diagnostic separately, and add successful output to an existing report. You will also deliberately replace one disposable capture to learn why an unsuccessful command does not protect an output file from redirection.

1. Establish the owned workspace

Complete Quote text and predict filename expansion first. Work in the checked Ubuntu guest as its ordinary Bash user. Use the already taught checks below. Run commands one line at a time and read the result before continuing. Stop after an unexpected error; the deliberately missing-path failures below are identified before their commands.

id -u
id -un
ps -p $ -o comm=
type printf set mkdir nano cat ls rm rmdir

Require a nonzero user ID, the expected username and Bash. printf and set should be Bash builtins; the utilities must have their expected installed origins. Preserve an understood color-only ls alias. Reconcile other origins before proceeding. Then use the taught read-only option inspection:

set -o

In this listing, require noclobber and errexit to be off: this exercise intentionally replaces one output and observes unsuccessful commands without ending the shell. If they differ, stop and reconcile the course baseline without changing settings here.

The only files this task changes belong to ~/linux-practice/redirect-command-streams/. Inspect the existing home and shared root using the taught metadata checks; no trailing slash is used when checking an entry itself:

ls -ld ~
ls -ld ~/linux-practice
ls -ld ~/linux-practice/redirect-command-streams

Existing parents must be ordinary directories, shown with leading d, owned by your recorded user. Stop on a link, unexpected owner or unrecognized path. The exercise entry must be absent for a fresh start. If it already exists, use the resume section instead of overwriting it.

Only after confirming absence, create and inspect the exercise directory:

mkdir ~/linux-practice/redirect-command-streams
ls -ld ~/linux-practice/redirect-command-streams

Require the expected ordinary directory and owner. Enter it separately from creating files:

cd ~/linux-practice/redirect-command-streams
pwd
ls -a

Require pwd to equal your recorded practice-root path followed by /redirect-command-streams, and require only . and .. in the listing. Do not continue from an unexpected location.

Supply the input and the existing report

Use the editor you already learned. In nano, enter the displayed text, save with Ctrl+O, confirm the exact filename with Enter, and exit with Ctrl+X. The saved file, rather than an unsaved editor buffer, is the input to later commands. First open the new input:

nano input.txt

Enter these two complete lines, pressing Enter after the second line too so the saved text ends with a newline:

Workshop input
Keep this line unchanged.

Inspect the directory again before opening the report:

ls -a

Require only the expected input and the dot entries; report.txt must still be absent. Then open it:

nano report.txt

Save these two lines, again pressing Enter after the second line. This final newline lets the later appended note begin on its own line:

Stream practice report
Existing line: keep me.

Check both saved files and their entire contents:

ls -ld -- input.txt report.txt
cat input.txt
cat report.txt
ls -a

Require ordinary regular files, shown with leading -, one link each and your expected owner. The two texts must match the supplied lines. No other entries should exist. In particular, missing.txt and missing-review.txt are names we intentionally leave absent. They are not starter files to create.

The task will create seven additional named captures: overwrite.txt, stdout.txt, stderr.txt, combined.txt, output-only.txt, review-output.txt and review-errors.txt. Each must be absent before its first creation. We will never redirect output over input.txt.

2. Three streams, three roles

A stream is a channel through which a command reads or writes data. A file descriptor is a small number identifying an open channel. The standard descriptors have stable roles:

NumberNameUsual role in this terminal task
0Standard input, or stdinData the command can read; initially connected to terminal input.
1Standard output, or stdoutThe command's normal result; initially displayed in the terminal.
2Standard error, or stderrThe command's diagnostics; initially also displayed in the terminal.

These are roles, not promises that every program puts every message on the right stream. In our chosen ls examples, a successful named-path listing goes to stdout and a missing-path diagnostic goes to stderr. Seeing both on the same terminal does not make them the same stream.

Redirection is Bash syntax that connects a descriptor to a different source or destination for a command. The redirection operators and filenames are handled by Bash; they are not ordinary arguments passed to ls or cat. The command's redirections end when that command finishes; they do not replace the terminal connections for all later commands.

The < operator opens the following file as standard input. With no filename argument, cat reads stdin and writes the data to stdout. Predict the text and the destination before running:

cat < input.txt

The two saved input lines appear in the terminal. Here descriptor 0 reads input.txt, and descriptor 1 still writes to the terminal. The input file has not been edited. This small observation makes stdin concrete without introducing another command connection.

3. Choose replacement or append before opening the output

> redirects stdout to its following filename. With our checked noclobber-off baseline, Bash creates an absent file or truncates an existing regular output file to zero length before the command executes. It then runs the command with stdout connected to that file. There is no interactive overwrite question from >.

>> instead opens the file for append: later output is added at its end. It also creates the file if absent, so a misspelled report name can create a new file while leaving the intended report unchanged. Inspect names first. Neither form gives permission to use an unknown file, a link or an input as the output destination.

The already taught printf '%s\n' format prints its following string and a newline. Before this new capture, inspect ls -a and require overwrite.txt absent. Then create just that output:

printf '%s\n' 'First capture' > overwrite.txt
ls -ld -- overwrite.txt
cat overwrite.txt

Require an owned regular single-link file containing exactly First capture. Now predict whether the next operation retains that line. Only after checking that this is the disposable output you just created, run:

printf '%s\n' 'Replacement capture' > overwrite.txt
cat overwrite.txt

The file contains only Replacement capture. The first line was replaced, not appended. This is an intentional change to this one disposable capture.

For the seeded report, choose append. Reinspect report.txt and its two original lines first:

ls -ld -- report.txt
cat report.txt

Require the same ordinary owned single-link file and both seed lines. Then:

printf '%s\n' 'Guided note: stream destinations checked.' >> report.txt
cat report.txt

The report should now contain the two seed lines followed by the guided note. If the seed is missing, stop and diagnose the operator or filename; do not silently reconstruct it and call the append successful.

An unsuccessful command can still empty the output

The taught ls -d form lists each named entry itself. For a regular input file it prints that filename; it reports a diagnostic for a missing path. -- ends ls option parsing. These commands inspect paths; they do not create the missing ones.

First verify that overwrite.txt still holds Replacement capture and that missing.txt remains absent in ls -a. Predict the result of this deliberately unsuccessful lookup:

ls -d -- missing.txt > overwrite.txt

The missing-path diagnostic should appear in the terminal because stderr was not redirected. Bash already opened and truncated overwrite.txt before ls discovered the missing path. Now inspect the effect:

ls -ld -- overwrite.txt
cat overwrite.txt

The output's size field should be zero, and cat should print no content. The former text is gone even though the lookup did not succeed. That expected failure teaches why “the command failed” is not a safe overwrite guard.

4. Capture the useful result and the diagnostic separately

2> redirects descriptor 2, stderr, to its following file. Keep 2 adjacent to >: writing a separated 2 would make it an ordinary argument instead. In the command below, unnumbered > means 1> and changes stdout. Both output files are created or truncated according to the same opening rules already taught for >.

Recheck input.txt and the absence of missing.txt. Inspect ls -a and require both stdout.txt and stderr.txt absent before their first creation. Predict which file will receive each kind of evidence:

ls -d -- input.txt missing.txt > stdout.txt 2> stderr.txt

This command has an intentional missing operand. It can list the existing input and still be unsuccessful overall. A successful-looking stdout line alone is not proof that every requested path was handled.

Inspect the captures separately:

ls -ld -- stdout.txt stderr.txt
cat stdout.txt
cat stderr.txt
cat input.txt

stdout.txt should contain the input.txt listing. stderr.txt should name the missing path and explain the lookup failure. An illustrative English diagnostic is ls: cannot access 'missing.txt': No such file or directory; wording, quotation and language can vary. Match the failed path and meaning, not an exact translated sentence. Both capture files must be owned ordinary single-link files. The original input must still contain its two supplied lines. Because both output channels were captured, the ls command itself normally leaves neither of these messages on the terminal.

The separate listing connects descriptor 1 to stdout.txt and descriptor 2 to stderr.txt; descriptor 0 remains terminal input and is unused by ls. Two later cases show that copying descriptor 1 into descriptor 2 before or after changing descriptor 1 gives different destinations.

Read the arrows as stream destinations for this ls command. The lower cases are processed from left to right: 2>&1 copies the current destination of stdout into stderr. The arrows show destinations, not a guaranteed order for text arriving from different streams.

5. Descriptor copies are processed from left to right

2>&1 means “make descriptor 2 use the destination that descriptor 1 uses at this point.” It does not name a file called 1, and it does not create a live link that follows every later change to descriptor 1. Bash processes the command's redirections in their written order.

Assume the command begins with stdout and stderr connected to the terminal. Inspect ls -a and require combined.txt and output-only.txt absent. Predict both destinations in each row before running either case:

Order writtenFirst stepSecond stepResult
> combined.txt 2>&1Stdout goes to combined.txt.Stderr copies that current stdout destination.Both output streams go to combined.txt.
2>&1 > output-only.txtStderr copies stdout's original terminal destination.Stdout moves to output-only.txt.Stdout goes to the file; stderr still goes to the terminal.

Run the first deliberately mixed-success lookup, then inspect its capture:

ls -d -- input.txt missing.txt > combined.txt 2>&1
cat combined.txt

The file should contain both the existing-path listing and the missing-path diagnostic. Check that both are present; do not use their relative order as evidence of which stream was redirected. Buffering and program behavior can change when each stream's text arrives.

Run the second case and observe the terminal before reading the file:

ls -d -- input.txt missing.txt 2>&1 > output-only.txt
cat output-only.txt

The ls diagnostic appears at the original stdout destination, the terminal. output-only.txt contains the successful listing without that diagnostic. The subsequent cat prints the stored listing on the terminal too: distinguish what you observed during ls from what you deliberately displayed afterward. Inspect both new files with the known metadata check:

ls -ld -- combined.txt output-only.txt

Require ordinary owned single-link captures. Reversing these two redirections changes where stderr goes; it does not change whether missing.txt exists.

Diagnose from destinations and saved evidence

ObservationPossible explanationSafe next check
No result appears in the terminal.Stdout may be redirected, or the command may have failed.Inspect the named stdout capture and stderr destination; silence alone proves neither success nor failure.
The output file is empty after an error.> opened it before the command failed.Compare its size and contents with the earlier record; do not redirect over a preserved input to “test again.”
The report lost its old lines.> was used where >> was required, or the wrong file was opened.Check the literal operator and path; stop and record the loss before a deliberate reset.
A new report-shaped filename appeared.>> can create a missing destination.Compare the exact name with report.txt and preserve an unrecognized entry.
A missing-path error appears despite 2>&1.That copy occurred before stdout moved to the file.Read the redirections left to right and identify stdout's destination at the copying step.
Bash reports that an output cannot be opened.The path or permissions prevented redirection.Check the exact directory, entry type and ownership. The intended command may never have started; do not broaden permissions.

A program's success or failure is also represented by an exit status: zero normally means success and nonzero indicates failure or another documented condition. Recall the earlier lesson's result and diagnostic distinctions. Here you check actual text, destinations and retained data; a capture file's existence does not establish command success. The next pipeline lesson teaches how to inspect status alongside the evidence from each stage.

Independent task: keep a report and isolate a new failure

Keep the guided state intact. Recheck the exact working directory, the saved input, and the report containing both seed lines plus the guided note. Require missing-review.txt absent, and require the new review-output.txt and review-errors.txt capture names absent before creating them.

Without opening the answer, construct and run these two operations, one at a time, using only this lesson's tools and operators:

  1. Ask ls -d to inspect only missing-review.txt. Capture stdout in review-output.txt and stderr separately in review-errors.txt.
  2. Ask ls -d to inspect the existing input.txt, and append that successful listing to the existing report.txt.

Before execution, predict whether the first stdout capture will contain a listing, which destination will contain its failure, and which earlier report lines must remain. Afterward, inspect the captures and the entire report. Check input.txt again. Do not create either missing path or use an input as an output destination.

Success: the first stdout capture is empty; the error capture identifies missing-review.txt; the report retains its previous three lines and adds an input.txt listing; the original input still matches both supplied lines. Explain why this is different from treating an empty stdout capture as a successful command with no interesting result.

Hints, from a small cue to a command plan

  1. Choose the two numbered output channels independently. The diagnostic belongs to descriptor 2, not to the useful-results report.
  2. The first lookup should have separate > and 2> destinations. For the second operation, preservation of earlier report text determines the operator.
  3. Use missing-review.txt as the first command's sole path operand. Use input.txt as the second command's sole path operand, with >> report.txt.

Answer and Reasoning

From the verified exercise directory, with the new capture names absent, one valid solution is:

ls -d -- missing-review.txt > review-output.txt 2> review-errors.txt

This lookup is intentionally unsuccessful. Bash creates the two captures; ls has no existing operand to list, so its stdout capture is empty. Its missing-path diagnostic goes to the error capture. Inspect before continuing:

ls -ld -- review-output.txt review-errors.txt
cat review-output.txt
cat review-errors.txt

Require the expected ordinary owned single-link files; the first should have size zero and the second should identify the intended missing operand. Then recheck the report's identity and prior content:

ls -ld -- report.txt
cat report.txt

Only after confirming the three retained lines, append the successful listing:

ls -d -- input.txt >> report.txt
cat report.txt
cat input.txt
ls -a

The report now has these four lines, with the listing's presentation subject to the understood listing configuration:

Stream practice report
Existing line: keep me.
Guided note: stream destinations checked.
input.txt

No missing-path diagnostic belongs in this report. input.txt remains the unchanged two-line input, and neither missing path exists. Alternatives are valid if they preserve those contents and destinations and supply the same separate failure evidence.

For the ordering check, > combined.txt 2>&1 copies the already changed file destination, while 2>&1 > output-only.txt copies the original terminal destination before stdout changes. For the overwrite check, opening and truncation precede command execution, so the unsuccessful lookup can leave overwrite.txt empty. File existence and apparent output order do not replace these destination and content checks.

Cleanup after the independent task

Finish all comparisons and record your explanations before cleanup. Inspect the shared-root and exercise entries again, rejecting links or unexpected owners:

ls -ld ~/linux-practice
ls -ld ~/linux-practice/redirect-command-streams

Enter and verify separately:

cd ~/linux-practice/redirect-command-streams
pwd

Require the exact recorded exercise path. Then inspect the full inventory and all nine expected files, without selecting targets by a wildcard:

ls -a
ls -ld -- input.txt report.txt overwrite.txt stdout.txt stderr.txt combined.txt output-only.txt review-output.txt review-errors.txt

Each must be a recognized ordinary file owned by the recorded user, with one link. Stop for an unrecognized entry, missing evidence, extra link or unexpected owner. Recheck any content you cannot identify. The two intentionally missing paths are not cleanup targets.

The shown y/n responses assume English confirmations. Establish the actual program's documented responses before removal; stop if its language or response convention is unclear. Only after all target checks, use named interactive removal:

rm -i -- input.txt report.txt overwrite.txt stdout.txt stderr.txt combined.txt output-only.txt review-output.txt review-errors.txt

Approve only the expected files. If stopping, decline the current and every remaining prompt: one n does not cancel later prompts. Inspect ls -a and require only . and .. before removing the directory.

First return to the shared root and verify it:

cd ~/linux-practice
pwd

Require pwd to equal the recorded shared-root path. Inspect the exercise entry itself before the separate removal:

ls -ld -- redirect-command-streams

Only for that recognized owned empty directory:

rmdir -- redirect-command-streams
ls -a

Retain the shared practice root and every unrelated lesson directory. No shell setting or system file needs restoring.

Resume or repeat deliberately

After an interruption, recheck the account, Bash options, parents, current location and each existing entry's identity. Inspect saved contents to find the last completed step; do not rerun every redirection. In particular, > replaces a capture and >> repeats an appended line. Keep evidence of an unexpected result before any reset.

For a known partial fixture, continue only from an identified state. Create only missing starter files through the taught editor, and never open an unknown existing capture for replacement. To repeat the entire comparison, inspect and remove only the recognized files actually created by this task, using named interactive removal and the same location guards. Leave unknown entries untouched. Rebuild the seed report and input in a fresh empty exercise directory before rerunning; simply appending again is not a reset.

Sources and other study views

The examples target the course's Bash 5.2 and GNU Coreutils 9.4 baseline. The upstream Coreutils manual can describe newer releases; the bounded forms used here do not establish compatibility for every newer option or default.

Use Revision to reconstruct the stream decisions, or Quick Reference to retrieve syntax after studying the full task.

Study this course with an account

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

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

See course access

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

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

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

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

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

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