Scripting and automationIntermediate23 min read

What Does Redirection Mean?

Reviewed byJohnson Ajibi· Senior Network & Security Engineer · MSc IT Security

This page mentions older exam versions. See the Current Exam Context and Legacy Exam Context sections below for the updated mapping.

On This Page

Quick Definition

Redirection is a way to take the output of a command and send it somewhere else, like a file, or take input from a file instead of the keyboard. It helps you automate tasks by controlling where data flows without manual copying. You can also use it to send errors to a separate file for troubleshooting. It's a fundamental tool in scripting and command-line work.

Commonly Confused With

RedirectionvsPiping

Piping (using |) sends the stdout of one command to the stdin of another command. Redirection sends output to a file or device. Piping keeps data within the command pipeline; redirection breaks the pipeline.

ls -la | grep .txt uses piping; ls -la > filelist.txt uses redirection.

RedirectionvsTee command

Tee (command | tee file.txt) sends output to both the screen and a file simultaneously. Redirection with > sends output only to a file, hiding it from the screen. Tee is a hybrid that allows you to see output as it is saved.

Instead of 'ls > file.txt' (output hidden), use 'ls | tee file.txt' to see output on screen and also save to a file.

RedirectionvsAppending vs overwriting

Both are forms of redirection, but > overwrites and >> appends. Some learners confuse the two operators, especially when the exam asks "Which operator adds to the end of a file without deleting existing content?"

echo 'first' > log.txt creates file with 'first'. echo 'second' >> log.txt adds a line with 'second' after the first line. Using > again would delete 'first'.

Must Know for Exams

Redirection is a direct objective in several major IT certification exams. For CompTIA A+ (220-1102), the exam objectives include "Given a scenario, use appropriate command-line tools." Redirection operators like >, >>, and | are part of that. You may be asked to show the command that saves the output of ipconfig to a file or to identify which operator appends output.

For CompTIA Linux+ (XK0-005), redirection is a major topic under "Data Manipulation" and "Shell Scripting." You must know how to redirect stdin, stdout, and stderr, understand file descriptors (0,1,2), and use here documents. Exam questions often ask you to fix a broken script by adding correct redirection operators.

In LPIC-1 (101-500, 102-500), redirection is tested in Topic 103: GNU and Unix Commands. Candidates need to demonstrate the use of >, >>, <, << (here document), 2>&1, and 2> to redirect errors. Performance-based items may require you to create a command that appends errors to a file while overwriting standard output.

For Red Hat Certified System Administrator (RHCSA) (EX200), redirection is essential for shell scripting and system administration. The exam includes creating scripts that redirect output to log files and handling errors appropriately. It's also used in the context of systemctl and journalctl when capturing logs.

Windows PowerShell questions in exams like Microsoft AZ-800 (Administering Windows Server Hybrid Core Infrastructure) and scripting sections of CompTIA Cloud+ include redirection operators such as >, Out-File, and *> to control output streams. Understanding the difference between > (equivalent to Out-File) and Out-File -Append is important.

redirection is often combined with pipes to chain commands, which appears in exam scenarios asking you to filter command output. For example, "Use a single command that lists all running processes, filters for a specific service, and saves the result to a file." The correct answer uses both pipe and redirection.

Multiple-choice and simulation questions may present a malformed command like "command 2>&1 > file" and ask what goes wrong. The correct reasoning is that stderr is redirected to the original stdout (screen), while stdout goes to file, so errors still appear on screen.

Therefore, for any exam covering command-line tools or scripting, expect at least two to three questions on redirection. It is a low-level skill that, if missed, can cost you points. Mastering redirection also helps in performance-based labs where you must type commands that produce correct output.

Simple Meaning

Think of redirection like a post office sorting mail. Normally, when you run a command on your computer, the result prints on the screen, that's like a letter going to your mailbox. Redirection lets you say, "Instead of the mailbox, send this letter to a special folder" (a file), or "Take the letter from that folder and read it aloud" (input from a file).

For everyday life, imagine you have a faucet pouring water into a bucket. That's standard output going to the screen. Redirection is like attaching a hose to the faucet to send the water to a plant across the yard (a file), or connecting a hose from a rain barrel to the faucet to pull water from there (input).

In computing, redirection uses symbols like > (send output to a file), < (read input from a file), and >> (append output to a file). For example, typing "dir > filelist.txt" sends the list of folder contents into a text file instead of showing it on the screen. This is incredibly useful when you need to keep logs, process data automatically, or build scripts that run without someone watching.

Redirection also separates different types of output: standard output (the good results), standard error (error messages), and standard input (what you type). By directing each to its own place, you can debug problems without missing important messages. Without redirection, every command would only talk to the screen, and you'd have to write down results by hand, not efficient for an IT pro managing hundreds of systems.

Full Technical Definition

Redirection in operating systems, particularly Unix-like systems (Linux, macOS) and Windows, refers to the ability to control where a command's input comes from (stdin) and where its output goes (stdout) and errors go (stderr). In Unix shells (bash, sh, zsh) and Windows PowerShell and cmd.exe, redirection operators change the default streams.

The three standard streams are: standard input (stdin, file descriptor 0), usually the keyboard; standard output (stdout, file descriptor 1), usually the terminal screen; and standard error (stderr, file descriptor 2), also the screen but separate from stdout. Redirection uses these file descriptors: 1> (redirect stdout) can be written as >, and 2> redirects stderr. The operator < redirects stdin from a file. For example, "command < input.txt" reads input from the file.

Common redirection operators: > overwrites a file; >> appends to a file; 2> overwrites the error file; 2>&1 merges stderr into stdout stream, useful when you want to capture both in one file. For example, "command > output.txt 2>&1" saves everything. Also, &> in bash does the same. The here document (<<) allows inline input, and the here string (<<<) passes a string as stdin.

Piping (|) is a special form of redirection that connects stdout of one command to stdin of another. For example, "ls -la | grep .txt" sends the list of files (stdout) directly to grep's stdin. This allows building powerful command chains.

In Windows cmd.exe, redirection operators are similar: >, >>, <, and 2> for stderr. The pipe | works the same. In PowerShell, redirection uses > (same as Out-File), but also cmdlets like Out-File, Select-Object, and the pipeline more deeply integrated with objects. PowerShell's redirection also supports 2>&1 and *> to redirect all streams.

Redirection is implemented at the kernel level; the shell sets up file descriptors before executing the command. When you redirect, the shell opens or creates the destination file, duplicates the descriptor using the dup2() system call, and then the command inherits these descriptors. The command itself doesn't know about the redirection, it just writes to its standard output.

In automation and scripting, redirection is essential for logging, error handling, and data processing. For example, a cron job that runs nightly can redirect all output and errors to a log file for later review. In DevOps and configuration management, redirection is used to capture command output for idempotent scripts and audit trails.

Understanding file descriptors and redirection operators is a core objective for CompTIA Linux+, LPIC-1, Red Hat Certified System Administrator (RHCSA), and many general IT certifications. It also appears in scripting sections of CompTIA A+ (command-line tools) and Network+ (troubleshooting with command-line utilities).

Potential pitfalls: overwriting files accidentally with > instead of >>, forgetting to handle stderr separately, or incorrect order of redirection (e.g., "command 2>&1 > file" actually redirects stderr to the original stdout, then stdout to file, likely not what you want). The correct order is "command > file 2>&1". Also, white space matters in some shells (e.g., "command > file" is the same as "command >file" in bash).

Real-Life Example

Imagine you are a chef preparing three different dishes for a busy dinner service. You have a single counter (your workspace) and you need to keep track of recipes, customer orders, and a to-do list. Normally, you would shout out orders to the team and everyone would hear everything. But that gets chaotic.

Redirection is like having three separate boards: one for recipes (standard output), one for urgent corrections (standard error), and one for spoken instructions (standard input). Instead of shouting, you write each order on the correct board. When you’re ready to cook, you read from the recipe board (input redirection, reading from a file instead of your memory). When you finish a dish, you write the completion time onto the output board (output redirection to a log file). If something burns, you write that on the error board (error redirection) to be reviewed later without cluttering the main log.

In IT, imagine you run a system update script. You want the normal update messages saved to one file, but error messages (like package not found) saved to a different file or to the same file for easy troubleshooting. Redirection lets you do that. Without it, you'd have to pipe everything through a filter manually, or worse, miss errors because they scrolled off the screen.

Another analogy: think of a library where you can check out books. Normally, you take books from the shelf (input) and return them to the cart (output). Redirection is like having a special return chute that sends the book directly to the restoration department (a different file) instead of the cart. Or, you have a request slip that pulls a book from the archive (input redirection) instead of the open shelves. This keeps the library organized and efficient.

So redirection is a way to manage information flow in a system, just as a chef or librarian manages physical items. It’s about routing data to the right place automatically, reducing manual effort and mistakes.

Why This Term Matters

Redirection is a foundational skill for any IT professional because it enables automation, reliable logging, and efficient troubleshooting. In day-to-day operations, system administrators use redirection to capture the output of scripts, cron jobs, and command-line tools into log files. Without redirection, you would need to babysit every command or rely on screen captures, both error-prone and inefficient.

For example, when you run a backup script that produces a list of files copied, you want that output saved to a log. Using redirection, you can send standard output to a log file and standard error to a separate error log, or even send both to the same file with timestamps. This makes it easy to audit the backup's success or failure later.

In scripting and automation, redirection is not just a convenience, it's a requirement for building robust scripts that can run unattended. Scripts that check for errors rely on capturing stderr. They can then parse the error file or check the exit code to decide what to do next. Redirection also allows you to suppress output when you don't need it (e.g., sending to /dev/null on Linux or NUL on Windows).

For help desk and support roles, understanding redirection helps when you need to capture output from diagnostic tools like ping, tracert, netstat, or ipconfig. You can redirect output to a text file and then analyze or share it with senior engineers. It's also essential for creating scripts that automate routine user management, disk checks, and network monitoring.

In an exam context, redirection appears in questions about command-line utilities, scripting, and troubleshooting. Being able to correctly use >, >>, 2>, 2>&1, and < is expected for certifications like CompTIA A+, Network+, Security+, Linux+, and many vendor-specific exams.

Finally, redirection is a gateway to more advanced concepts like pipelining, which is itself a form of redirection. Mastering redirection helps you think in terms of data flow, which is crucial for understanding modern infrastructure technologies like CI/CD pipelines, configuration management, and log aggregation systems.

How It Appears in Exam Questions

Exam questions about redirection take several forms: direct knowledge of operators, command composition, and troubleshooting.

Direct knowledge questions: "Which operator redirects standard error to a file?" Choices include >, 2>, &>, 2>&1. The correct answer is 2>. Or, "What does >> do?" (Appends output to an existing file, or creates it if it doesn't exist). These are straightforward but require memorization.

Command composition questions: "Given a log file of errors called errors.txt, which command would add new error output to this file without overwriting existing content?" The correct syntax would be something like "command 2>> errors.txt". Another example: "Which command runs a script and sends both standard output and error to the same file?" Answer: "script.sh > output.txt 2>&1" or in bash "script.sh &> output.txt".

Troubleshooting questions: "A script is supposed to write success messages to success.log and errors to error.log, but errors also appear in success.log. What is the issue?" The likely cause is incorrect order of redirection, such as "2>&1 > success.log" instead of "> success.log 2>&1". The candidate needs to explain the file descriptor order.

Simulation questions require you to type the correct command. For example: "Use redirection to save the output of the ping command (10 pings to 8.8.8.8) to a file called ping_results.txt, and ensure error messages are saved to ping_errors.txt." The correct answer: "ping -n 10 8.8.8.8 1> ping_results.txt 2> ping_errors.txt" (Windows) or "ping -c 10 8.8.8.8 1> ping_results.txt 2> ping_errors.txt" (Linux).

Another pattern: "You need to run a diagnostic script and capture all output, including errors, to analyze later. Which command would you use?" Options may include "script > log.txt 2>&1", "script 2> log.txt", "script &> log.txt", etc. The correct answer in Linux is either first or third depending on the shell.

Performance-based items: "Create a script that does a directory listing, filters for .txt files, counts them, and writes the count to a file named count.txt." The script might involve ls, grep, wc, and redirect the final count.

Also, knowing that > overwrites and >> appends is tested. A question might say: "A student writes a script that logs the timestamp every hour. They notice the file always contains only the last timestamp. What is the fix?" Answer: Change > to >>.

Finally, exam questions may test the concept of null devices: "You want to run a command but suppress all output. Which redirection destination do you use?" Answer: /dev/null (Linux) or NUL (Windows).

Practise Redirection Questions

Test your understanding with exam-style practice questions.

Practise

Example Scenario

You are an IT support specialist for a company with 200 Windows workstations. Your manager asks you to check which computers have a specific piece of software installed (version 2.1.0). You decide to run a PowerShell command remotely on each machine that checks the installed programs. Normally, each result would appear on your screen, but you want to store all the data in a text file for later review.

You create a script called software_check.ps1 that loops through a list of computer names and runs 'Get-WmiObject -Class Win32_Product | Where-Object {$_.Version -eq "2.1.0"}' on each. Without redirection, when you run the script, the output scrolls by and you cannot easily see which computers have the software, and error messages (like computer unreachable) mix with results.

To solve this, you use redirection. You run the script like this:

./software_check.ps1 > successful_computers.txt 2> errors.txt

This sends all successful results (stdout) to the file successful_computers.txt, and all error messages (stderr) to errors.txt. If a computer is offline, you will see the error in errors.txt without it interrupting the results list.

Later, you can open successful_computers.txt to see which computers already have version 2.1.0, and errors.txt to see which ones need a manual check. You could even append the next day's results using >> instead of >, so the file keeps growing for trend analysis.

This scenario shows how redirection makes your job efficient: you get clean, separated logs, and you don't have to sit watching the screen. In an exam, they might ask you what the correct command is to achieve this. The answer would involve > and 2> or, in PowerShell, *> to capture all streams. Understanding which stream goes where is key.

Common Mistakes

Using > when you should use >>, erasing previous log data.

The > operator overwrites the destination file completely, losing all previous records. In logging, you almost always want to append, not overwrite.

Always think: do you want to keep old data? If yes, use >> to append. If you're starting fresh, use > but be sure you don't need the old file.

Mixing up the order of redirection in 2>&1, e.g., 'command 2>&1 > file'.

The order matters because file descriptors are duplicated left to right. In 'command 2>&1 > file', stderr is sent to the current stdout (screen), then stdout is sent to file. So stderr still appears on screen, not the intended behavior.

Always redirect stdout first, then merge stderr: 'command > file 2>&1'. Or use shorthand &> in bash.

Thinking that > redirects standard error by default.

By default, > only redirects stdout (file descriptor 1). To redirect stderr, you must explicitly use 2>.

Remember: 1> (or >) for normal output, 2> for errors. If you want both, use 2>&1 after stdout redirection.

Forgetting the space between operator and filename, e.g., 'command>file.txt' in shells that require spaces.

Most shells allow no space (e.g., 'command>file.txt' works in bash). However, some older shells or Windows cmd might treat 'command>file.txt' differently. Also, when using 2>&1, no space before &1 can cause parsing issues.

Add spaces for clarity: 'command > file.txt' and 'command > file.txt 2>&1'. Consistency helps avoid confusion.

Assuming redirection works the same in PowerShell as in cmd.

In cmd, > redirects text output. In PowerShell, > is an alias for Out-File, which may encode the file differently (Unicode vs ASCII) and can cause issues when the file is read by other tools. Also, PowerShell has multiple streams (Write-Output, Write-Error, etc.) that require different syntax.

In PowerShell, use Out-File -FilePath .\file.txt -Encoding ASCII for compatibility. Use *> to redirect all streams, or use specific stream redirection like 2> for error.

Not understanding that /dev/null is a valid redirection target on Unix-like systems but not on Windows.

Windows doesn't have /dev/null; it uses NUL (without colon). Using /dev/null in a Windows command will cause an error.

Use 'command > NUL' on Windows to suppress output, and 'command 2> NUL' to suppress errors. On Linux/macOS, use /dev/null.

Exam Trap — Don't Get Fooled

{"trap":"An exam question shows 'command 2>&1 > file' and asks which stream goes to the file. Many learners think both stdout and stderr go to file.","why_learners_choose_it":"Learners assume that 2>&1 merges stderr into stdout, and then the redirection > file applies to the merged stream.

But because of the order, stderr is first redirected to the current stdout (screen), then stdout is redirected to file, so stderr stays on screen.","how_to_avoid_it":"Read redirection from left to right. First, 2>&1 sends stderr to where stdout is currently going (the screen).

Second, > file changes stdout to go to file. After that, stderr is still going to the old location (screen). The fix is to do stdout first: > file 2>&1. In bash, use &> file to capture both safely."

Step-by-Step Breakdown

1

Identify the streams

Every process has three standard file descriptors: 0 (stdin, input), 1 (stdout, normal output), and 2 (stderr, error output). In a terminal, all three connect to the keyboard and screen by default.

2

Choose the destination

Decide where you want stdout and stderr to go: a file (text file, log), a device (/dev/null, NUL), or another command (pipeline). For redirection to a file, you must specify the filename.

3

Use the correct operator

Use > (or 1>) to overwrite a file with stdout. Use >> (or 1>>) to append stdout. Use 2> for stderr, and 2>> to append stderr. Use < to read input from a file.

4

Combine streams if needed

If you want both stdout and stderr in the same file, add 2>&1 after redirecting stdout, or use &> (shorthand in bash). For example: command > log.txt 2>&1 or command &> log.txt.

5

Execute and verify

Run the command. After execution, check the destination file(s) to ensure the output is correctly captured. Use cat (Linux) or type (Windows) to view the file. Verify that errors are where you expected them.

6

Handle special cases

For suppressing output, redirect to /dev/null (Linux) or NUL (Windows). For here documents (<<), use to provide inline input. For here strings (<<<), pass a string as stdin. For example: cat << EOF ... EOF is a here document.

Practical Mini-Lesson

Redirection is a practical tool that every sysadmin and DevOps engineer uses daily. Let’s dive into a realistic scenario: automating log collection for a web server.

Suppose you have a script that runs daily at 2 AM to check disk space, CPU load, and memory. You want all output saved to a file, but errors need to be highlighted. You write a cron job like:

0 2 * * * /usr/local/bin/system_check.sh > /var/log/system_check_$(date +\%Y\%m\%d).log 2>&1

This redirects both stdout and stderr to a date-stamped log file. But what if the script fails because of a permission issue? The error goes to the log, but you might miss it until you check the file. A better approach: redirect stderr to a separate error log, and also pipe errors to your monitoring system.

In a professional environment, you may also need to use redirection with tee to see live output while saving to a file. For example:

./deploy.sh 2>&1 | tee -a deploy.log

This lets you watch the deployment progress in real time and also keeps a permanent log. Tee is not redirection per se, but it uses redirection internally.

Another aspect: managing input from files. Suppose you have a list of servers in servers.txt and you want to run a command against each. You can use input redirection:

while read -r server; do ssh $server "uptime"; done < servers.txt

Here, < servers.txt feeds the list of server names to the while loop, one per iteration. This is a common pattern for batch administration.

What can go wrong? Accidental overwriting is the most common. If you use > in a cron job that runs often, the log only contains the last run. Always use >> for ongoing logs, or include date stamps. Another common issue is permission denied when writing to /var/log. The script may not have write permission, so the redirection fails silently (if errors are redirected to a file that cannot be opened, the error goes to the screen, assuming stderr is not redirected).

For Windows professionals, redirection is used in batch files and PowerShell. In a batch file, you might do:

ping 8.8.8.8 > result.txt 2> error.txt

In PowerShell, you use:

Get-Process > process_list.txt 2> errors.txt

Note that PowerShell's > may produce Unicode output, which can break downstream text tools. To force ASCII, use Out-File -Encoding ASCII.

mastering redirection means you can build scripts that are self-documenting, resilient, and easy to debug. The key is to think about data flow: where does the output come from, where should it go, and what happens when things fail.

Memory Tip

Remember "1 for output, 2 for errors", the file descriptor numbers: 1> (or >) goes to output, 2> goes to errors. To get both in one file, think "2 goes to 1", i.e., 2>&1.

Covered in These Exams

Current Exam Context

Current exam versions that test this topic — use these objectives when studying.

Legacy Exam Context

Older materials may mention these exam versions, but learners should use the current objectives for their target exam.

XK0-005XK0-006(current version)

Related Glossary Terms

Frequently Asked Questions

What is the difference between > and >> in redirection?

> overwrites the target file with the new output, deleting any existing content. >> appends the new output to the end of the file, preserving previous content. Use > for fresh logs and >> for accumulating logs.

How do I redirect both standard output and standard error to the same file?

In bash and sh, use: command > file 2>&1 or the shorthand command &> file. In Windows cmd, use: command > file 2>&1. In PowerShell, use: command *> file or command 2>&1 > file.

What is /dev/null and why would I redirect to it?

/dev/null is a special file on Unix-like systems that discards all data written to it. It's often used to suppress unwanted output. For example, command > /dev/null discards stdout, and command 2> /dev/null discards errors.

Does redirection work the same in Windows cmd and PowerShell?

Not exactly. In cmd, > redirects text output. In PowerShell, > is an alias for Out-File, which can produce Unicode files. PowerShell also has multiple streams (6 through 9) and uses *> to redirect all streams. Always be aware of encoding and stream numbers.

What is the purpose of 2>&1 in redirection?

2>&1 means "redirect file descriptor 2 (stderr) to wherever file descriptor 1 (stdout) is currently going." This merges error messages into the same output stream, so both can be captured in the same file or pipeline.

What happens if I redirect stderr after stdout redirection in the wrong order?

If you write command 2>&1 > file, stderr goes to the original stdout (screen), then stdout is redirected to file. So errors still appear on screen. Always write stdout first: command > file 2>&1.

Can I use redirection in scripts that run as cron jobs?

Yes, it's highly recommended. Cron jobs run without a terminal, so output would be lost unless redirected to a file or email. Always redirect both stdout and stderr to log files for debugging.

Summary

Redirection is a core concept in scripting and automation that allows you to control the flow of data from commands to files, devices, or other commands. It uses standard streams (stdin, stdout, stderr) and operators like >, >>, 2>, 2>&1, and < to manage input and output. Understanding redirection is crucial for anyone working with command-line tools, as it enables automatic logging, error handling, and efficient data processing.

In the exam context, redirection appears in multiple-choice, simulation, and troubleshooting questions across CompTIA A+, Linux+, LPIC-1, RHCSA, and Windows Server certifications. Common mistakes include confusing > with >>, misordering 2>&1, and forgetting that stderr is separate from stdout. By mastering the order of redirection and the meaning of each operator, you can avoid these traps.

Real-world use cases include saving system logs, building automated scripts, and handling errors in batch operations. Redirection also lays the groundwork for more advanced concepts like pipelines, which are essential for DevOps and system administration.

Key takeaway: always know your file descriptors, use the correct operator for the job (overwrite vs. append), and remember the order of redirection. Practice by writing simple commands that redirect output to files and then examine the contents. This hands-on experience will solidify your understanding and prepare you for both the exam and the field.