> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Input Output Redirection eg 2

> Describes Linux shell input and output redirection, stderr handling, here-docs and here-strings, and using pipes to connect commands.

In this lesson we'll cover input and output redirection in Linux — how to route data into and out of programs using the shell. These techniques let you save program output to files, separate error messages from normal output, feed files as program input, and connect small utilities together with pipes.

## Example: sort reads stdin and writes stdout

Many Unix utilities follow the convention of reading from standard input (stdin) and writing to standard output (stdout). For example, `sort` reads lines of text and writes them in order.

Suppose `file.txt` contains:

```text theme={null}
6
5
1
3
4
2
```

Running `sort file.txt` reads `file.txt` and prints sorted lines to the terminal (stdout):

```bash theme={null}
$ sort file.txt
1
2
3
4
5
6
```

To save that sorted output to a file instead of printing to the terminal, use output redirection with `>`:

```bash theme={null}
$ sort file.txt > sortedfile.txt
$ cat sortedfile.txt
1
2
3
4
5
6
```

If the target file does not exist, `>` creates it. By default `>` overwrites the file; use `>>` to append instead:

```bash theme={null}
$ date > file.txt   # overwrite
$ date >> file.txt  # append
$ cat file.txt
Mon Nov  8 18:50:30 CST 2021
Mon Nov  8 18:51:10 CST 2021
```

The forms `>` and `1>` are equivalent because file descriptor `1` is stdout:

```bash theme={null}
date > file.txt
date 1> file.txt
```

### Standard streams and file descriptors

Programs use three standard streams by default:

* Standard Input (`stdin`) — file descriptor 0
* Standard Output (`stdout`) — file descriptor 1
* Standard Error (`stderr`) — file descriptor 2

Use `<` to redirect standard input, `>` (or `1>`) to redirect standard output, and `2>` to redirect standard error.

![A diagram illustrating Unix standard streams: file.txt is fed as stdin into the sort command, the command’s stdout goes to the terminal (1>), and stderr is redirected to errors.txt (2>).](https://mintcdn.com/kodekloud-c4ac6d9a/wxtIfjNk9A2S4_uP/images/Prep-Course-Linux-Foundation-Certified-System-Administrator-LFCS-Certification/Essential-Commands/Use-Input-Output-Redirection-eg-2/unix-sort-stdin-stdout-stderr-errors.jpg?fit=max\&auto=format\&n=wxtIfjNk9A2S4_uP\&q=85\&s=18dcc4d048471abef220a0985882df3c)

## Redirecting stderr (error messages)

Many commands print error messages to stderr (fd 2). For example:

```bash theme={null}
$ grep -r '^The' /etc/
grep: /etc/cups/ssl: Permission denied
grep: /etc/cups/subscriptions.conf.O: Permission denied
...
/etc/brltty/Input/tn/all.txt:The two keys at the left rear (2 columns, 1 row):
...
```

If you want to discard error messages (so they don't clutter the terminal), redirect stderr to `/dev/null`:

```bash theme={null}
$ grep -r '^The' /etc/ 2>/dev/null
/etc/brltty/Input/tn/all.txt:The two keys at the left rear (2 columns, 1 row):
...
```

`/dev/null` discards anything written to it — useful when you want to ignore unwanted output such as diagnostic or permission errors.

You can redirect stdout and stderr to separate files — either overwrite or append:

```bash theme={null}
# Overwrite both files
$ grep -r '^The' /etc/ 1>output.txt 2>errors.txt

# Append to both files
$ grep -r '^The' /etc/ 1>>output.txt 2>>errors.txt
```

## Capture both stdout and stderr into a single file

To capture both streams into the same file, redirect stdout first, then point stderr at stdout using `2>&1`:

```bash theme={null}
$ grep -r '^The' /etc/ >all_output.txt 2>&1
```

Explanation:

* `>all_output.txt` redirects stdout (fd 1) to `all_output.txt`
* `2>&1` directs stderr (fd 2) to wherever fd 1 currently points (the file)

Order matters when combining redirections. Use `>file 2>&1` (or `1>file 2>&1`) to ensure both stdout and stderr go to `file`. Placing `2>&1` before `>file` will leave stderr pointing at the terminal.

Incorrect ordering example (does not capture stderr into the file):

```bash theme={null}
# Incorrect: stderr will still go to the terminal
$ grep -r '^The' /etc/ 2>&1 1>all_output.txt
```

Safer, clearer alternatives:

```bash theme={null}
$ grep -r '^The' /etc/ 1>all_output.txt 2>&1
# or equivalently
$ grep -r '^The' /etc/ >all_output.txt 2>&1
```

## Redirecting stdin (feeding input)

Redirecting input is less common but useful when a program reads from stdin (fd 0). Use `<` to feed a file as input:

```bash theme={null}
$ sendemail someone@example.com < emailcontent.txt
```

This makes the program read `emailcontent.txt` as if the content were typed at the keyboard.

### Here-documents (multi-line stdin)

A here-document (here-doc) embeds multi-line input directly in the command:

```bash theme={null}
$ sort <<EOF
> 6
> 3
> 2
> 5
> 1
> 4
> EOF
1
2
3
4
5
6
```

`EOF` is a common delimiter; any marker works. All text between the start and the delimiter is passed to the program's stdin.

### Here-strings (single-line stdin)

A here-string passes a single line/string as stdin using `<<<`:

```bash theme={null}
$ bc <<< "5 * (2 + 3)"
25
```

Here-docs and here-strings are handy for scripting or automating programs that expect keyboard input.

## Pipes: chain small programs

Pipes (`|`) let you chain utilities so the stdout of one becomes the stdin of the next. Example: remove comment lines, sort the entries, and align columns for readability:

```bash theme={null}
$ grep -v '^#' /etc/login.defs | sort | column -t
CREATE_HOME        yes
ENCRYPT_METHOD     SHA512
GID_MAX            60000
GID_MIN            1000
HOME_MODE          0700
MAIL_DIR           /var/mail
PASS_MAX_DAYS      99999
PASS_MIN_DAYS      0
PASS_MIN_LEN       5
PASS_WARN_AGE      7
SYS_GID_MAX        999
SYS_GID_MIN        201
SYS_UID_MAX        999
SYS_UID_MIN        201
UID_MAX            60000
UID_MIN            1000
UMASK              022
USERGROUPS_ENAB    yes
```

Pipes are powerful for composing small, focused tools (the Unix philosophy) without creating temporary files.

## Quick reference

| Operator | Meaning | Example |
| - | - | - |
| `>` or `1>` | Redirect stdout (overwrite file) | `command > out.txt` |
| `>>` or `1>>` | Append stdout | `command >> out.txt` |
| `2>` | Redirect stderr (overwrite) | `command 2> err.txt` |
| `2>>` | Append stderr | `command 2>> err.txt` |
| `2>&1` | Redirect stderr to wherever stdout currently points | `command >both.txt 2>&1` |
| `<` | Redirect stdin from a file | `command < infile.txt` |
| `<<EOF ... EOF` | Here-doc: multi-line stdin | see example above |
| `<<<` | Here-string: single-line stdin | `grep foo <<< "one-line"` |
| `\|` | Pipe stdout into next command's stdin | `cmd1 \| cmd2` |

## Further reading

* [Bash Reference Manual — Redirections](https://www.gnu.org/software/bash/manual/html_node/Redirections.html)
* [Linux /dev/null — Wikipedia](https://en.wikipedia.org/wiki/Null_device)

Summary

* Use `>`/`>>` for stdout redirection and `2>`/`2>>` for stderr.
* Use `2>&1` to combine stderr with stdout (mind the order).
* Use `<`, here-docs (`<<`), and here-strings (`<<<`) to feed stdin.
* Use pipes (`|`) to connect programs without intermediate files.

> **[Watch Video](https://learn.kodekloud.com/user/courses/linux-foundation-certified-system-administrator-lfcs/module/115b1db7-7970-4cc8-91d4-0ac4892fed9f/lesson/2721d1fa-f098-4355-aa67-ce3a57f7711b)**

> **[Practice Lab](https://learn.kodekloud.com/user/courses/linux-foundation-certified-system-administrator-lfcs/module/115b1db7-7970-4cc8-91d4-0ac4892fed9f/lesson/c67b99b5-0f90-41fa-ac4e-221f95686cb6)**


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.